Part 3: Python Programming
Part 3: Python Programming — read through each chapter in order. Diagrams, tables and worked examples included.
4. Strings in Python
Strings in Python
A string is a sequence of characters: letters, digits, spaces, and symbols. Strings represent all the text your programs handle, from names to whole documents. This chapter covers how to create strings, pick them apart, and transform them.
Creating strings
You write a string inside matching single or double quotes. Both are equal; choose whichever avoids clashing with quotes inside the text. For text spanning several lines, use triple quotes:
Indexing and slicing
Each character has a position called an index, starting at 0 for the first character. Negative indexes count from the end, where -1 is the last character. A slice [start:stop] returns the characters from start up to but not including stop.
f-strings
The cleanest way to build a string that includes variable values is the f-string. Put the letter f before the opening quote and write expressions inside curly braces:
Common string methods
Strings come with many built-in methods, called with a dot. Here are the ones you will use most.
| Method | What it does | Example | Result |
|---|---|---|---|
.upper() | All uppercase | "hi".upper() | "HI" |
.lower() | All lowercase | "HI".lower() | "hi" |
.strip() | Remove surrounding spaces | " hi ".strip() | "hi" |
.split() | Break into a list | "a b c".split() | ['a','b','c'] |
.replace() | Swap text | "cat".replace("c","h") | "hat" |
.find() | Index of first match (-1 if none) | "hello".find("l") | 2 |
Immutability
Strings are immutable: once created, they cannot be changed in place. Every method that seems to "change" a string actually returns a brand-new string, leaving the original untouched:
The first s.upper() created "CAT" but we did not store it, so s was unchanged. Only when we reassign s does the variable point to the new value. Remember this pattern: use the return value.