Programming and IT

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.

Updated
In this article

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:

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:

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.

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:

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#

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:

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:

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 — slices work on strings the same way as on lists — and Python regular expressions for when the plain search methods are not enough.

Step-by-step plan

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

Start learning this in your own space

The plan goes into your repository: tick off stages, keep notes — the change history shows how far you have come.

Start the plan

Check yourself

1.What does print(", ".join(["a", "b", "c"])) print?

2.What does the call "report.txt".strip(".txt") do?

3.What is len("abc" * 3)?

4.What does "she sells sea shells".find("ocean") return?

Sources

Was this helpful?

More articles

Programming and IT Python: slicing A slice cuts a piece out of a sequence by the rule "from which index, up to which, with what step". The notation is compact, but it has two places where almost everyone slips: the right bound is not included, and with a negative step the bounds swap places. Let us go through both. Programming and IT Python: lists A list is a mutable, ordered collection of values of any type. It is also the main source of surprises for beginners: assignment does not copy a list, sort returns nothing, and removing items inside a loop skips half of them. Let us go through it in order. Programming and IT Python: dictionaries A dictionary stores key–value pairs and finds a value by its key in constant time, however large it grows. It is the workhorse for counting, grouping and settings. Below: creating dictionaries, safe access, iteration and the places where a dictionary does not behave the way people expect. Programming and IT Python: decorators A decorator is a function that takes another function and returns a new one with extra behaviour. The `@` sign above a definition is just a shorthand for an assignment. Keep that in mind and the whole topic takes one evening. Programming and IT Python: practice problems with solutions A set of problems in order of difficulty — from reversing a string to a generator and a call-counting decorator. Solve each one yourself first and only then open the walkthrough: comparing your code with someone else's teaches more than reading a finished answer. All solutions are tested on Python 3. Programming and IT How to learn Python from scratch Python is a good first programming language: code reads almost like text, and the standard library covers most everyday tasks. This plan takes you from installing the interpreter to your own scripts covered by tests in about four months, at roughly an hour a day.

More solutions