Python: Quote String

By Xah Lee. Date: . Last updated: .

Quote String

Use single quote or double quote.

# python 3

a = "this "
b = 'and that'
print(a, b)

String Escape

Use \n for linebreak, and \t for tab.

# python 3

a = "this\nthat\n"    # use \n for line-break

b = 'more\nthings'    # single quote works too

print(a, b)

# output:

# this
# that
#  more
# things

Here's complete list of escape sequence:

\'
Single quote
\"
Double quote
\newline
Ignored
\\
Backslash
\a
ASCII Bell
\b
ASCII Backspace
\f
ASCII Formfeed
\n
ASCII Linefeed
\r
ASCII Carriage Return
\t
ASCII Horizontal Tab
\ooo
Character with octal value ooo
\xhh
Character with hexadecimal value hh
\uxxxx
Unicode codepoint hexadecimal value xxxx
\Uxxxxxxxx
Unicode codepoint hexadecimal value xxxxxxxx
\v
ASCII Vertical Tab
\N{name}
Unicode character named name

Raw string (No Backslash Escape)

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

# python 3

c = r"this \n and that"

print(c) # prints a single line

Quote Multi-Lines

To quote a string of multiple lines, use triple quotes.

# python 3

d = """this
will be printed
in 3 lines"""

print(d)

# output:

# this
# will be printed
# in 3 lines

Summary

Python 2: If your string contain literal Unicode chars, such as α, then prefix your string with “u”, like this: u"greek α". But you also need to add a declaration #-*- coding: utf-8 -*-. The “r” and “u” can be combined, like this: ur"I ♥ Python" See: Python: Unicode Tutorial 🐍 .

Python 2, String Containing Unicode

Add u in front of the quote symbol if you string contains unicode characters. e.g. u"I ♥ U". It can be combined with r, e.g. ur"/I ♥ U/", and can also used in front of triple quote.

# -*- coding: utf-8 -*-
# python 2

# raw string
s1 = r"a\nb"

print(len(s1) == 4) # True
# -*- coding: utf-8 -*-
# python 2

s2 = ur"/I♥U/"

print len(s2) == 5 # True

Python String

Python

Regex

Text Processing

Web

Misc