# Python: strings

A string in Python is an immutable sequence of characters. Almost all of its quirks follow from that: methods do not change a string but return a new one, and fast text building goes through join, not through adding strings in a loop. Below is the working minimum with examples and output.

## What a string is and why you cannot change it

A string is written in single, double or triple quotes — there is no difference
between `'a'` and `"a"`, and triple quotes are for multi-line text. The language
has no separate "character" type: `"cat"[0]` is a string of length one.

The key property is immutability. Trying to overwrite a character fails:

```python
s = "cat"
s[0] = "b"
  # TypeError: 'str' object does not support item assignment
```

That is why every string method returns a new value and leaves the original as it
was. A common beginner mistake is calling a method and forgetting to assign the
result:

```python
name = "  Anna  "
name.strip()
print(repr(name))   # '  Anna  '
name = name.strip()
print(repr(name))   # 'Anna'
```

## Cutting and joining: split and join

The two operations you need most are splitting a string into parts and gluing
parts into a string.

```python
line = "apple,pear,,plum"
print(line.split(","))      # ['apple', 'pear', '', 'plum']
print("  a   b  ".split())  # ['a', 'b']
```

`split(",")` cuts at every occurrence, so two separators in a row give an empty
string in the list. Calling `split()` with no argument behaves differently: it
splits on any whitespace, merges runs of it and drops whitespace at the edges.

The reverse operation is `join`. The method is called on the separator, not on
the list, and every item must already be a string:

```python
print(", ".join(["a", "b", "c"]))  # a, b, c
print(", ".join([1, 2]))
  # TypeError: sequence item 0: expected str instance, int found
print(", ".join(str(x) for x in [1, 2]))  # 1, 2
```

## Finding, replacing, checking

```python
text = "she sells sea shells"
print("sells" in text)         # True
print(text.find("sea"))        # 10
print(text.find("ocean"))      # -1
print(text.count("se"))        # 2
print(text.replace("s", "S", 1))  # She sells sea shells
```

`find` returns the index of the first occurrence, or `-1` if there is none;
`index` does the same but raises `ValueError` when the substring is missing. The
third argument of `replace` limits the number of replacements.

For checks, use `startswith`, `endswith` and the `is*` family: `"2026".isdigit()`
is `True`, but `"12.5".isdigit()` is already `False`, because a dot is not a
digit. This method is a reliable number check only for unsigned whole numbers.

## f-strings instead of adding

Building text by adding strings is clumsy and it is easy to forget about types:
`"total " + 5` fails with `TypeError`. An f-string inserts any value and can format
it at the same time:

```python
price = 1234.5678
name = "tea"
print(f"{name}: ${price:,.2f}")         # tea: $1,234.57
print(f"{name!r} has {len(name)} letters")  # 'tea' has 3 letters
print(f"{42:>6}|")                      # "    42|"
```

Inside the braces is an ordinary expression, and after the colon comes the
format: `.2f` means two digits after the point, `>6` right-aligns in a width of
six, `,` adds a thousands separator. `!r` prints the value the way `repr` would
show it — handy for debugging, because you can see the quotes and spaces.

## Traps everyone falls into

**`strip` takes a set of characters, not a substring.** This is the most popular
mistake:

```python
print("report.txt".strip(".txt"))        # repor
print("report.txt".removesuffix(".txt"))  # report
```

`strip(".txt")` removes any characters from the set `{'.', 't', 'x'}` from both
ends — and it does not stop at the extension, it also eats the `t` at the end of
`report`. To cut off an exact ending, use `removesuffix` and `removeprefix`
(available since Python 3.9).

**Concatenating in a loop.** `result += chunk` inside a long loop creates a new
string every time. It is better to collect the parts in a list and call `join`
once.

**Case and comparison.** `"Hello".lower()` gives `"hello"`, but for case-insensitive
comparison `casefold()` is better — it handles other alphabets more carefully:
`"Straße".lower()` stays `"straße"`, while `"Straße".casefold()` gives
`"strasse"`.

A small final task: take the string `"Smith; 35; London"`, split it into three
fields, remove the extra spaces and put it back together as
`"London | Smith (35)"` — with one f-string and no `+`.

Next, look at [Python slicing](https://skillok.org/topics/python-slicing) — slices work on strings
the same way as on lists — and [Python regular expressions](https://skillok.org/topics/python-regex)
for when the plain search methods are not enough.

## Step-by-step plan

1. **Check immutability** — In the interactive shell, assign to s[0] and see the TypeError; then do the same through replace.
2. **Run ten methods** — upper, lower, strip, split, join, replace, find, count, startswith, removesuffix — print the result of each.
3. **Build a table with f-strings** — Print five lines aligned to a fixed width with two digits after the point.
4. **Parse a data line** — Take the string "name;age;city", cut it with split and join it back with a different separator.
5. **Catch the strip trap** — Compare strip(".txt") with removesuffix(".txt") on the name report.txt and write down the difference.

## Check yourself

1. What does print(", ".join(["a", "b", "c"])) print?
   - a, b, c
   - ['a', 'b', 'c']
   - abc
   - a,b,c
2. What does the call "report.txt".strip(".txt") do?
   - Removes any of the characters dot, t, x from both ends
   - Cuts off exactly the .txt ending
   - Replaces the extension with an empty string
   - Checks that the name ends with .txt
3. What is len("abc" * 3)?
4. What does "she sells sea shells".find("ocean") return?

## Sources

- [String methods in the Python docs](https://docs.python.org/3/library/stdtypes.html) — The full list of str methods with their arguments
- [An Informal Introduction to Python](https://docs.python.org/3/tutorial/introduction.html) — The official tutorial chapter that introduces strings
- [Format Specification Mini-Language](https://docs.python.org/3/library/string.html) — Everything that can go after the colon in an f-string

---

https://skillok.org/articles/en/python-strings
