🐍 Python

Updated at 2018-06-09 14:44

Strings are immutable and recursive sequences of Unicode characters.

assert type('abc') == str
assert 'abc'[0] == 'a'
assert type('abc'[0]) == str
assert type('abc'[0][0][0][0][0]) == str

Prefer single quoted strings '. You can also create strings with double quotes ", but single quotes ' are the ones that e.g. Python print directive will give around strings in a list.

# bad
text: str = "This is a string."

# good
text: str = 'This is also a string.'

Use parenthesis to form multiline strings. Will not work without the parenthesis.

text: str = ('This will build a very long long '
             'long long long long long long string')

Build strings using sequences. Use join() when glueing a string sequence together. Faster because does not create a new string like + does.

# bad
chars = ['S', 'a', 'f', 'e']
name = ''
for char in chars:
    name += char
assert name == 'Safe'

# good
chars = ['S', 'a', 'f', 'e']
name = ''.join(chars)
assert name == 'Safe'

# good
employee_list = [['John', 'Doe'], ['Mary', 'Lee']]
items = ['<table>']
for last_name, first_name in employee_list:
    items.append(f'<tr><td>{last_name}, {first_name}</td></tr>')
table = ''.join(items)
assert table == '<table><tr><td>John, Doe</td></tr><tr><td>Mary, Lee</td></tr></table>'


  • Python Tricks The Book, Dan Bader
  • Fluent Python, Luciano Ramalho