Strings

Slicing, f-strings, the methods you actually use, and why joins beat concatenation in loops.

Creating and slicing

s = 'Python'
print(s[0])     # P
s[-1]           # n      negative index counts from the end
s[0:2]          # 'Py'    end index is exclusive
s[::-1]         # 'nohtyP' reversed
len(s)          # 6

print('py' in s.lower())   # True - membership test
πŸ’‘
Strings are immutable β€” every "change" creates a new one. That is why s[0] = 'p' raises TypeError.

Methods worth memorizing

MethodResult
s.strip()Removes leading/trailing whitespace
s.lower()/s.upper()Case folding
s.split(',')List of parts
','.join(parts)Inverse of split
s.replace(a, b)All occurrences
s.startswith(p)Boolean prefix test
s.find(p)Index or -1 (no exception)
csv = ' a, b , c '
fields = [f.strip() for f in csv.strip().split(',')]
print(fields)  # ['a', 'b', 'c']

path = '/var/log/app.log'
path.rsplit('/', 1)[-1]     # 'app.log'  - split from the right

Building strings efficiently

# slow: each += allocates a brand new string
out = ''
for line in lines:
    out += line + '\n'

# fast: one pass, one allocation
out = '\n'.join(lines)
⚠️
Repeated concatenation inside loops is quadratic in practice. Append to a list and join once β€” the standard idiom.

Text vs bytes

Python 3 keeps a clear boundary: str is Unicode text, bytes is raw data. Convert explicitly at the edges of your program β€” reading files, network sockets.

'cafΓ©'.encode('utf-8')          # b'caf\xc3\xa9'
b'caf\xc3\xa9'.decode('utf-8')  # 'cafΓ©'

with open('notes.txt', encoding='utf-8') as f:
    text = f.read()
⚠️
Always pass encoding= to open(). Omitting it relies on the platform default, so the same code reads fine on Linux and breaks on Windows.

FAQ

Single or double quotes?
Interchangeable. Pick one, and use the other when the string itself contains a quote character to avoid escaping.
How do I make a multi-line string?
Triple quotes: '''text'''. Great for embedded SQL or docs; note it preserves indentation, so use textwrap.dedent.

UTF-8 and character sets Python: getting started

Last refreshed 2026-09-17.