Python: Quote String
Strings are enclosed using single quote or double quote. example
# -*- coding: utf-8 -*- # python a = "this " b = 'and that' print a, b # prints 「this and that」
You can use
\n for linebreak, and
\t for tab, etc.
Complete list of escape sequences: 2. Lexical analysis — Python v2.7.6 documentation#string-literals
# -*- coding: utf-8 -*- # python a = "this\nthat\n" # use \n for line-break b = 'more\nthings' # single quote works too print a, b # prints # this # that # more # things
You can add
r in front of the quote symbol. This way, backslash characters will be interpreted as is, not as escapes. (“r” for “raw”)
# -*- coding: utf-8 -*- # python c = r"this\n and that" print c # prints literally 「this\n and that」, single line
To quote a string of multiple lines, use triple quotes. Example:
# -*- coding: utf-8 -*- # python xx = """aa bb cc""" print xx # prints the following, 3 lines # aa # bb # cc
Python string quote 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.
rin front of your quoting char (For example,
r"hot") if you want backslash to be literal.
- If your string is 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 🐍.
- 2. Lexical analysis — Python v2.7.6 documentation#string-literals
- 5. Built-in Types — Python v2.7.6 documentation #typesseq
Ask me question on patreon