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
ASCII Backspace
ASCII Formfeed
ASCII Linefeed
ASCII Carriage Return
ASCII Horizontal Tab
Character with octal value ooo
Character with hexadecimal value hh
Unicode codepoint hexadecimal value xxxx
Unicode codepoint hexadecimal value xxxxxxxx
ASCII Vertical Tab
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"""


# output:

# this
# will be printed
# in 3 lines


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



Text Processing