Python: Quote String
Use single quote or double quote.
# python 3 a = "this " b = 'and that' print(a, b)
\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 Bell
- 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)
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
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
- 'Single' quote and "double" quote chars are equivalent. (linebreak in your string is not allowed. It's syntax error.)
- The backslash char is a char escape mechanism.
rin front of your quoting char (For example,
r"hot") if you want backslash to be literal.
- For multiple lines, use triple
'''single'''quote or triple
"""double"""quote. You can still prefix
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
u in front of the quote symbol if you string contains unicode characters.
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