Python: Quote String

By Xah Lee. Date: . Last updated: .

A string is a sequence of characters.

(in Python 3, it's a sequence of Unicode characters.)

(in Python 2, it's a sequence of bytes (representing ASCII Characters). But if prefixed with u, then it's a sequence of Unicode characters.)

Quote String by One Double Quote or One Single Quote

String can be created by "one double quote" or 'one single quote'.

"one double quote" and 'one single quote' delimited strings are effectively the same.

xx = "this is string"

yy = 'another string'

print(xx, yy)

Literal linebreak is not allowed. It's syntax error.

a = "abc
xyz"
print(a)

#     a = "abc
#             ^
# SyntaxError: EOL while scanning string literal
error: cannot format -: Cannot parse: 1:3: a = "abc
b = "that"
print(b)

String Escape, Backslash

Inside string:

r for Raw string (No Backslash Escape)

Add r in front of the quote symbol. This way, backslash characters is interpreted as is, not as escapes. (β€œr” for β€œraw”)

xx = r"this \n and that"

print(xx)
# prints literally:
# this \n and that
# a single line

Triple Quote for Multi-Lines String

To quote a string of multiple lines, use triple quotes. The quote character can be "one double quote" or 'one single quote'.

xx = """this
is
tree lines"""

print(xx)

# this
# is
# tree lines

The string can also be prefixed with raw r.

xx = """aa\nbb
cc"""

print(xx)

# aa
# bb
# cc

# raw string. interpret blackslash literally
yy = r"""aa\nbb
cc"""

print(yy)

# aa\nbb
# cc

Python 2, String Containing Unicode

Python, String