You're being mislead by output -- the second approach you're taking actually does what you want, you just aren't believing it. :)

Copy>>> foo = 'baz "\\"'
>>> foo
'baz "\\"'
>>> print(foo)
baz "\"

Incidentally, there's another string form which might be a bit clearer:

Copy>>> print(r'baz "\"')
baz "\"
Answer from Charles Duffy on Stack Overflow
Top answer
1 of 5
116

You're being mislead by output -- the second approach you're taking actually does what you want, you just aren't believing it. :)

Copy>>> foo = 'baz "\\"'
>>> foo
'baz "\\"'
>>> print(foo)
baz "\"

Incidentally, there's another string form which might be a bit clearer:

Copy>>> print(r'baz "\"')
baz "\"
2 of 5
57

Use a raw string:

Copy>>> foo = r'baz "\"'
>>> foo
'baz "\\"'

Note that although it looks wrong, it's actually right. There is only one backslash in the string foo.

This happens because when you just type foo at the prompt, python displays the result of __repr__() on the string. This leads to the following (notice only one backslash and no quotes around the printed string):

Copy>>> foo = r'baz "\"'
>>> foo
'baz "\\"'
>>> print(foo)
baz "\"

And let's keep going because there's more backslash tricks. If you want to have a backslash at the end of the string and use the method above you'll come across a problem:

Copy>>> foo = r'baz \'
  File "<stdin>", line 1
    foo = r'baz \'
                 ^  
SyntaxError: EOL while scanning single-quoted string

Raw strings don't work properly when you do that. You have to use a regular string and escape your backslashes:

Copy>>> foo = 'baz \\'
>>> print(foo)
baz \

However, if you're working with Windows file names, you're in for some pain. What you want to do is use forward slashes and the os.path.normpath() function:

Copymyfile = os.path.normpath('c:/folder/subfolder/file.txt')
open(myfile)

This will save a lot of escaping and hair-tearing. This page was handy when going through this a while ago.

🌐
University of Pittsburgh
sites.pitt.edu › ~naraehan › python3 › mbb6.html
Python 3 Notes: Comments and Strings Expanded
Python 3 Notes [ HOME | LING 1330/2330 ] Tutorial 6: Comments and Strings Expanded << Previous Tutorial Next Tutorial >> On this page: commenting with #, multi-line strings with """ """, printing multiple objects, the backslash "\" as the escape character, '\t', '\n', '\r', and '\\'. Video ...
Discussions

regex - In Python, how can you write the string String = "\s"? - Stack Overflow
Releases Keep up-to-date on features ... Stack Internal. ... pythonjavascriptc#reactjsjavaandroidhtmlflutterc++node.jstypescriptcssrphpangularnext.jsspring-bootmachine-learningsqlexceliosazuredocker ... Next You’ll be prompted to create an account to view your personalized homepage. ... Save this question. Show activity on this post. ... Closed 3 years ago. ... I have read similar questions on both the issue of backslashes, and their ... More on stackoverflow.com
🌐 stackoverflow.com
Backslash error
I’m having some issues with backslashes in my scripts and in python in general. I am using the latest version of python. I downloaded python to an external drive because I lack some storage space. Using command prompt D:\python-lang>python.exe pip install numpy python.exe: can't open file ... More on discuss.python.org
🌐 discuss.python.org
3
0
November 4, 2023
The use of slash in python string and regex - Stack Overflow
Actually, what I'm asking is that: In Python, if I want to match whitespace, the regex and the String I input could both be "\s", right? However, in Java, the regex should be "\s", while the String should be "\\s". The two languages seem to treat String "\s" differently. Why? ... Is it the same in other languages like Java? -- Yes, backslashes ... More on stackoverflow.com
🌐 stackoverflow.com
What does a backslash by itself ('\') mean in Python? - Stack Overflow
See the Line Structure section of the Python reference documentation: Two or more physical lines may be joined into logical lines using backslash characters (\), as follows: when a physical line ends in a backslash that is not part of a string literal or comment, it is joined with the following ... More on stackoverflow.com
🌐 stackoverflow.com
🌐
W3Schools
w3schools.com › python › gloss_python_escape_characters.asp
Python Escape Characters
Study Plan Python Interview Q&A Python Bootcamp Python Training ... To insert characters that are illegal in a string, use an escape character. An escape character is a backslash \ followed by the character you want to inser...
🌐
Python Tutorial
pythontutorial.net › home › python basics › python backslash
Python Backslash \
March 30, 2025 - Second, the backslash (\) escape other special characters. For example, if you have a string that has a single quote inside a single-quoted string like the following string, you need to use the backslash to escape the single quote character: s = '"Python\'s awesome" She said' print(s)Code language: ...
Find elsewhere
🌐
Quora
quora.com › How-do-you-backslash-a-string-in-Python
How to backslash a string in Python - Quora
Single backslash: use a doubled backslash in the string literal: "\" -> produces a one-character string containing . Multiple backslashes: double each one inside the literal: "\\" -> produces two backslashes. ... Prefix with r to avoid escaping most backslashes: r"C:\Users\Alice\file.txt" is convenient. ... To include literal backslashes in Python strings you must escape each backslash (write \) or use raw string literals when appropriate...
🌐
Python.org
discuss.python.org › python help
Backslash error - Python Help - Discussions on Python.org
November 4, 2023 - I’m having some issues with backslashes in my scripts and in python in general. I am using the latest version of python. I downloaded python to an external drive because I lack some storage space. Using command prompt …
Top answer
1 of 2
1

So it seems that python would convert \sto \s.

Don't confuse string representations with the actual content of the string. String representation is the way you write a string in source code, which may not exactly be the same as the string actually in memory. Backslashes are parsed specially to allow you to write non-printable characters using the backslash syntax. In this case, \s is not a valid escape sequence so the python parser interprets it literally as backslash-s. In memory, the string is still a character sequence containing the letters: `\, s

str class have a __repr__()/repr() method that returns a string that contains the source-code representation of the string, this is the string that gets printed when you don't use print statement in the REPL. This allows you to copy paste those string and reuse it in another part of the shell, but it isn't really what is stored in memory and how python interprets the string. When printing repr, python always escapes a literal backslash, this is to remove ambiguity on whether the backslash is interpreted as escape sequence or as a literal character.

Why would Python do this and what is this for? Is it the same in other languages like Java?

Most languages' string literal do interpret backslash escape sequence, although different languages treats invalid escape sequence differently. In Python, invalid backslash escape sequence is silently treated as literal backslash instead of producing an error. You'd probably encounter this kind of issue more often in Python because it has an ubiquitous repr() protocol and the default use of repr in the REPL shell.

2 of 2
1

Python is just escaping it, so when it sees an "\" continued by a letter and if that letter doesn't have any special meaning then Python actually escapes the backslash, instead of throwing any errors.

Python interactive interface uses repr to return a string containing a printable representation of an object. So that function is adding the extra backslash to indicate that it's a literal backslash.

If you use print function to show the value of str1, you will get it printed in the stdout with just 1 backslash.

Look at this example:

str1 = '\s'

print str1
print str1.__repr__()
Top answer
1 of 5
43

A backslash at the end of a line tells Python to extend the current logical line over across to the next physical line. See the Line Structure section of the Python reference documentation:

2.1.5. Explicit line joining

Two or more physical lines may be joined into logical lines using backslash characters (\), as follows: when a physical line ends in a backslash that is not part of a string literal or comment, it is joined with the following forming a single logical line, deleting the backslash and the following end-of-line character. For example:

if 1900 < year < 2100 and 1 <= month <= 12 \
   and 1 <= day <= 31 and 0 <= hour < 24 \
   and 0 <= minute < 60 and 0 <= second < 60:   # Looks like a valid date
        return 1

There is also the option to use implicit line joining, by using parentheses or brackets or curly braces; Python will not end the logical line until it finds the matching closing bracket or brace for each opening bracket or brace. This is the recommended code style, the sample you found should really be written as:

if ((i < len(words_and_emoticons) - 1 and item.lower() == "kind" and
        words_and_emoticons[i+1].lower() == "of") or
        item.lower() in BOOSTER_DICT):
    sentiments.append(valence)
    continue

See the Python Style Guide (PEP 8) (but note the exception; some Python statements don't support (...) parenthesising so backslashes are acceptable there).

Note that Python is not the only programming language using backslashes for line continuation; bash, C and C++ preprocessor syntax, Falcon, Mathematica and Ruby also use this syntax to extend lines; see Wikipedia.

2 of 5
4

In this case, the \ is escaping the following new line character. Because Python cares about whitespace, this code is using this to allow code to be continued on a new line.

🌐
Python documentation
docs.python.org › 3 › library › re.html
re — Regular expression operations — Python 3.14.5 ...
2 weeks ago - The solution is to use Python’s raw string notation for regular expression patterns; backslashes are not handled in any special way in a string literal prefixed with 'r'. So r"\n" is a two-character string containing '\' and 'n', while "\n" is a one-character string containing a newline.
🌐
AskPython
askpython.com › home › raw strings in python: a comprehensive guide
Raw Strings in Python: A Comprehensive Guide - AskPython
May 22, 2023 - Also read: 4 Handy Ways to Convert Bytes to Hex Strings in Python 3 · To understand what a raw string exactly means, let’s consider the below string, having the sequence “\n”. ... Now, since s is a normal string literal, the sequences “\t” and “\n” will be treated as escape characters. So, if we print the string, the corresponding escape sequences (tab-space and new-line) will be generated. ... # s is now a raw string # Here, both backslashes will NOT be escaped.
🌐
freeCodeCamp
forum.freecodecamp.org › python
Regex confusion: '\S' vs '\\S' - Python - The freeCodeCamp Forum
August 19, 2023 - I’m working my way through the Scientific Computing with Python track taught by Doc Chuck Severance. I just finished watching the “Regular Expressions: Matching and Extracting Data” video, and I’m confused about the ques…
🌐
DigitalOcean
digitalocean.com › community › tutorials › python-raw-string
How To Use Python Raw String | DigitalOcean
March 4, 2026 - When the Python interpreter encounters a normal string like 'Hello\nWorld', it processes \n as a newline character during compilation. With a raw string like r'Hello\nWorld', the interpreter keeps \n as two literal characters: a backslash followed by n.
🌐
Acid & Base
sceweb.sce.uhcl.edu › helm › WEBPAGE-Python › documentation › howto › regex › node8.html
3.2 The Backslash Plague
In short, to match a literal backslash, one has to write '\\\\' as the RE string, because the regular expression must be "\\", and each backslash must be expressed as "\\" inside a regular Python string literal.
🌐
Finxter
blog.finxter.com › home › learn python blog › how to do a backslash in python?
How to Do a Backslash in Python? - Be on the Right Side of Change
March 8, 2023 - The backslash \ is an escape character–if used in front of another character, it changes the meaning of this character. For example, the character 'n' is just that a simple character, but the character '\n' (yes, it’s one character consisting ...
🌐
Python documentation
docs.python.org › 3 › reference › lexical_analysis.html
2. Lexical analysis — Python 3.14.5 documentation
Unless an ‘r’ or ‘R’ prefix ... used by Standard C. The recognized escape sequences are: A backslash can be added at the end of a line to ignore the newline:...
🌐
py4u
py4u.org › blog › python-regex-to-replace-double-backslash-with-single-backslash
How to Replace Double Backslash with Single Backslash in Python Using Regex: Fixing Common Escape Errors
Backslashes (\) are a common source of confusion in Python, especially when dealing with file paths, user input, JSON data, or text parsing. Due to Python’s use of backslashes as escape characters (e.g., \n for newline, \t for tab), strings ...
🌐
Python documentation
docs.python.org › 3 › howto › regex.html
Regular expression HOWTO — Python 3.14.5 documentation
Let’s say you want to write a RE that matches the string \section, which might be found in a LaTeX file. To figure out what to write in the program code, start with the desired string to be matched. Next, you must escape any backslashes and other metacharacters by preceding them with a backslash, resulting in the string \\section.