Escape quotes in Python

'It\'s "ready"'

'It\'s "ready"' is the string It’s “ready” in Python. The backslash keeps the single quote from ending the string, and double quotes inside single quotes need nothing. Double quotes move the problem to the other quote, and triple quotes need neither:

a = 'It\'s "ready"'
b = "It's \"ready\""
c = '''It's "ready"'''
print(a, a == b == c)
# It's "ready" True

repr writes the literal for you

repr() returns the literal Python would write for a string, escapes included. It picks single quotes unless the string holds a single quote and no double quote:

print(repr(a))
print(repr("It's"))
print(repr('C:\\temp\n'))
'It\'s "ready"'
"It's"
'C:\\temp\n'

The tool below writes the single-quoted form, so its Python escape of It's "ready" is It\'s "ready", what repr puts between the quotes. For JSON, use json.dumps, not repr: JSON has no single-quoted strings.

Raw strings

In a raw string, r'…', a backslash is just a backslash, which suits Windows paths and regular expressions. But a raw string can’t end in one backslash, because the backslash still keeps the quote after it from closing the string:

path = r'C:\temp\'
# SyntaxError: unterminated string literal (detected at line 1); perhaps you escaped the end quote?

That’s also why r'\'' is two characters, a backslash and a quote. Write the path as 'C:\\temp\\', or as r'C:\temp' + '\\', which is the same string.

Without the r, a backslash before a letter that isn’t an escape, like \d, stays in the string, and Python 3.12 and later warn about it:

SyntaxWarning: "\d" is an invalid escape sequence. Such sequences will not work in the future. Did you mean "\\d"? A raw string is also an option.

The tool’s Unescape rejects it outright: \d is not a Python escape.

Triple quotes

Triple-quoted strings take both quotes and line breaks as they are. The catch is a quote at the very end, which runs into the closing three:

print("""She said "hi"""")
# SyntaxError: unterminated string literal (detected at line 1)

Escape that last quote, """She said "hi\"""", or close with the other kind, '''She said "hi"'''.

f-strings

In an f-string, a literal brace is doubled: f'{{name}} is {name}' prints {name} is Ann. Since Python 3.12 (PEP 701), the expressions inside the braces can also hold backslashes and the f-string’s own quotes:

items = ["It's", '"ready"']
print(f"{'\n'.join(items)}")
print(f"{", ".join(items)}")
It's
"ready"
It's, "ready"

Python 3.11 rejects the first line with SyntaxError: f-string expression part cannot include a backslash and the second with SyntaxError: f-string: expecting '}'. There, join into a variable first, or use the other kind of quote inside.

Try it in the String Escape & Unescape

12 of up to 100,000 characters

Single-quote literal rules: \ and ' are escaped, " stands as it is.

Result
It\'s "ready"

Runs in your browser. Nothing you enter is sent anywhere.