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()
'abcDef'.capitalize()
'Abcdef'
Casefold for caseless matching casefold()
'abcDef'.casefold()
'abcdef'
Center center(width, fillchar = ' ')
'abcDef'.center(10)
'  abcDef  '
'abcDef'.center(4)
'abcDef'
'abcDef'.center(10, '-')
'--abcDef--'
Count count(substring, [start], [end])
'abc abc abc'.count('abc')
3
'abc abc abc'.count('abc', 2)
1
'abc abc abc'.count('abc', 2, 8)
1
'abc abc def'.count('def')
0
'abc abc def'.count('')
11
Encode to bytes encode(encoding = 'utf-8')
'abc'.encode()
b'abc'
Ends with endswith(suffix, [start], [end])
'abcdefghi'.endswith('ghi')
True
'abcdefghi'.endswith('def')
False
'abcdefghi'.endswith(('ghi', 'abc'))
True
'abcdefghi'.endswith(('def', 'abc'))
False
'abcdefghi'.endswith('def', 1, 6)
True
Expand tabs into spaces expandtabs(tabsize = 8)
'a\tb\tc'.expandtabs()
'a        b        c'
'a\tb\tc'.expandtabs(2)
'a  b  c'
Find string find(substring, [start], [end])
'abc abc abc'.find('abc')
0
'abc abc abc'.find('abc', 2, 8)
4
'abc abc abc'.find('def')
-1