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
yth

Positive 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 old

f-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.

📝 Quick Quiz

1. What does `"Hello"[1]` return?

2. Which quotes create a multi-line string?

3. The best modern way to format strings is: