Python · Chapter 8 of 45
Python Strings
A string is a sequence of characters wrapped in single or double quotes. Strings are immutable — you cannot change a character in place, you make a new string.
Use triple quotes for multi-line strings.
Indexing and slicing
Access characters by index starting at 0. Slice with `s[start:stop:step]` where stop is exclusive.
f-strings (formatted strings)
Prefix a string with `f` to embed expressions with `{...}`. This is the modern, preferred way to format text.
Example 1 (python)
s = "Python"
print(s[0])
print(s[-1])
print(s[1:4])Output
P
n
ythPositive indices count from the left, negative from the right.
Example 2 (python)
name = "Ana"
age = 24
print(f"{name} is {age} years old")Output
Ana is 24 years oldf-strings embed variables directly.
Key points
- Strings are immutable — modifying makes a new string.
- Index starts at 0; -1 is the last character.
- Slice with `s[start:stop:step]`.
- Use f-strings for formatting: `f"{var}"`.
💡 Note: Concatenating many strings with `+` is slow. Use `"".join(list)` or f-strings for performance.
