Python Strings
A. Basic Strings
single_quote = 'Hello World!'
double_quote = "Hello World!"
single_with_special_chars = 'String with \'escaped\' quotes.'
double_with_special_chars = "First line\nSecond Line with \"escaped\" quotes and other chars: \t \r \\ \$."
triple_single_quoted = '''This is effectively a multiline string.
New lines and single quotes work natively.
String with 'escaped' quotes.'''
triple_double_quoted = """This is effectively a multiline string.
New lines and double quotes work natively.
String with 'escaped' quotes."""
B. Extended/Special Characters
// Octal notation (ABC)
octal = '\101\102\103'
// Hexidecimal notation (ABC)
hexdec = '\x41\x42\x43'
// Named Unicode Character notation (ABC)
named_unicode = '\N{LATIN CAPITAL LETTER A}\N{LATIN CAPITAL LETTER B}\N{LATIN CAPITAL LETTER C}'
// Hexidecimal Unicode Character notation (ABC)
hexdec_unicode_short = '\u0041\u0042\u0043'
hexdec_unicode_long = '\U00000041\U00000042\U00000043'
C. Byte Literals
series_of_bytes = b'\x89PNG\r\n\x1a\n'
raw_string = r'\d{4}-\d{2}-\d{2}'
raw_bytes = rb'\x89PNG\r\n\x1a\n'
D. Formatted Strings
who = 'nobody'
nationality = 'Spanish'
f'{who.title()} expects the {nationality} Inquisition! {{ The Pope did! }}'
//> Nobody expects the Spanish Inquisition! { The Pope did! }
name = 'Galahad'
favorite_color = 'blue'
print(f'{name}:\t{favorite_color}')
//> Galahad: blue
print(rf"C:\Users\{name}")
C:\Users\Galahad
print(f'''Three shall be the number of the counting
and the number of the counting shall be three.''')
//> Three shall be the number of the counting
and the number of the counting shall be three.
D. Template Strings
who = 'nobody'
nationality = 'Spanish'
t'{who.title()} expects the {nationality} Inquisition!'
E. String Methods
| Description | Signature | Syntax Example | Result |
|---|---|---|---|
| Capitalize first letter | capitalize() | |
|
| Casefold for caseless matching | casefold() | |
|
| Center | center(width, fillchar = ' ') | |
|
|
|
||
|
|
||
| Count | count(substring, [start], [end]) | |
|
|
|
||
|
|
||
|
|
||
|
|
||
| Encode to bytes | encode(encoding = 'utf-8') | |
|
| Ends with | endswith(suffix, [start], [end]) | |
|
|
|
||
|
|
||
|
|
||
|
|
||
| Expand tabs into spaces | expandtabs(tabsize = 8) | |
|
|
|
||
| Find string | find(substring, [start], [end]) | |
|
|
|
||
|
|