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.
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:
=
=
# 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:
=
# ' Anna '
=
# '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.
=
# ['apple', 'pear', '', 'plum']
# ['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:
# a, b, c
# TypeError: sequence item 0: expected str instance, int found
# 1, 2
Finding, replacing, checking#
=
# True
# 10
# -1
# 2
# 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:
= 1234.5678
=
# tea: $1,234.57
# 'tea' has 3 letters
# " 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:
# repor
# 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
- Check immutabilityIn the interactive shell, assign to s[0] and see the TypeError; then do the same through replace.
- Run ten methodsupper, lower, strip, split, join, replace, find, count, startswith, removesuffix — print the result of each.
- Build a table with f-stringsPrint five lines aligned to a fixed width with two digits after the point.
- Parse a data lineTake the string "name;age;city", cut it with split and join it back with a different separator.
- 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.
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
-
String methods in the Python docsThe full list of str methods with their argumentsfree
-
An Informal Introduction to PythonThe official tutorial chapter that introduces stringsfree
-
Format Specification Mini-LanguageEverything that can go after the colon in an f-stringfree
Was this helpful?