Python: Quote String
What is String
A string is a sequence of characters.
- In Python 3, it's a sequence of Unicode characters.
- In Python 2, it's a sequence of bytes (representing ASCII Characters). But if prefixed with
u
, then it's a sequence of Unicode characters.
Python string is immutable. Any function that work on string returns a new string.
Quoting String
Two ways to quote a string.
- Singe quote. e.g.
"abc"
→ does not allow literal newline. - Triple quote. e.g.
"""abc"""
→ for multi-line string. (allow literal newline)
String Delimiter
String can be quoted by QUOTATION MARK
e.g. "abc"
or
APOSTROPHE
e.g.
'abc'
.
There is no different between them.
No Here-String
Python does not suport here-doc or here-string, as in Perl, PHP, PowerShell.
Single Quote String
String can be created by:
"QUOTATION MARK delimited"
'APOSTROPHE delimited'
they are effectively the same.
Literal linebreak is not allowed. It's syntax error.
xx = "this is string" yy = 'another string' print(xx, yy)
# Literal linebreak is not allowed xx = "abc xyz" # xx = "abc # ^ # SyntaxError: EOL while scanning string literal # error: cannot format -: Cannot parse: 1:3: a = "abc
Triple Quote String
String Prefix Char
a character may be prefixed to a string, to make the string of a particular type.
prefix chars:
u"abc"
→ means unicode string, in python 2. In python 3, all string are Python: Unicode 🐍, the u prefex has no meaning.f"abc"
→ means f-String, where{…}
means embedded expression.r"abc"
→ means Raw String. Escape Sequence is ignored.b"abc"
→ means byte sequence.
these prefix characters may be combined.
e.g. fr"abc"
means can embed expression and also raw (ignore Python: String Escape Sequence)
String Escape
Inside string (except Raw String ):
- Use
\n
for linebreak. - Use
\"
for double quote. - Use
\'
for single quote.
Python, String
- Python: Quote String
- Python: Triple Quote String
- Python: Raw String
- Python: f-String (Format, Template)
- Python: String Escape Sequence
- Python: Unicode Escape Sequence
- Python: Print String
- Python: Print Without Newline
- Python: Convert to String
- Python: Join String
- Python: Format String
- Python: String Methods
- Python: Search Substring
- Python: Split String
- Python: String, Check Case, Char Class
- Python: Letter Case Conversion
- Python: Unicode 🐍
- Python 2: Unicode Tutorial