Python: Quote String
Summary
- '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.
- Prefix
r
in 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 prefixr
in front.
Quote String
Use single quote or double quote.
a = "this " b = 'and that' print(a, b)
String Escape
Use \n
for linebreak, and \t
for tab.
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”)
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.
d = """this will be printed in 3 lines""" print(d) # output: # this # will be printed # in 3 lines
Python 2, String Containing Unicode
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 🐍
.
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