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.
String is Immutable
Any function that work on string returns a new string.
String Syntax
there are several syntax for string.
# single quoted string aa = "single QUOTATION MARK" bb = 'single APOSTROPHE'
# triple quoted string cc = """triple QUOTATION MARK""" dd = '''triple APOSTROPHE'''
Single Quoted String
single quoted string is designed for short string, like few words or one sentence.
in single quoted string:
- Literal newline character is not allowed. It's syntax error.
- Backslash character in string has special interpretation. see String Escape Sequence, unless the starting delimiter is prefixed with
r, known as Raw String (r-prefix)
# single quoted string # APOSTROPHE delimited yy = 'good morn' print(yy) # good morn
# single quoted string # QUOTATION MARK delimited xx = "good eve" print(xx) # good eve
# in single quoted string, literal linebreak character is not allowed xx = "abc xyz" # xx = "abc # ^ # SyntaxError: unterminated string literal (detected at line 3)
What's the difference between QUOTATION MARK, and APOSTROPHE as string delimiters
- QUOTATION MARK quoted string cannot contain QUOTATION MARK.
- APOSTROPHE quoted string cannot contain APOSTROPHE.
To include the delimiter in the string, you need to use String Escape Sequence, or Triple Quote String .
Triple Quote String
No Here-String
Python does not support Here-String (aka here-doc)