Python 101Free
FOUNDATIONS

Strings

Text as a sequence of characters, and the methods you reach for daily.

SECTION 01

Indexing and slicing

A Python string is a sequence of characters with zero-based indexing. "hello"[0] is "h". Negative indices count from the end, so "hello"[-1] is "o". The bracket form picks one character.

Slicing picks a range. "hello"[1:4] is "ell". The slice is half-open, the start is included, the end is not. Either bound can be omitted and an optional third value sets the step. "hello"[::-1] reverses the string by stepping backwards.

Slicing always produces a new string. Strings are immutable, so there is no way to modify one in place. Any operation that looks like it changes a string is actually returning a new one and rebinding the name.

python
s = "hello"
s[0]      # 'h'
s[-1]     # 'o'
s[1:4]    # 'ell'
s[::-1]   # 'olleh'
SECTION 02

Common methods

Four string methods carry most of the weight in everyday code. split breaks a string on a separator into a list of pieces. strip removes whitespace (or any specified characters) from both ends. replace substitutes one substring for another. join is the inverse of split, gluing a list of strings back together.

Note that join is a method on the separator, not on the list. ", ".join(parts) reads slightly oddly at first but matches the rest of the API. The separator is what you have on hand, the list is what you are doing the work on.

Every string method returns a new string. They never mutate. Chaining them is fine and idiomatic, name.strip().lower().replace(" ", "_") is normal Python.

python
"  Ada Lovelace  ".strip().lower().replace(" ", "_")
# 'ada_lovelace'

"a,b,c".split(",")     # ['a', 'b', 'c']
"-".join(["a", "b"])   # 'a-b'
SECTION 03

F-strings and formatting

An f-string is a regular string with an f in front, where curly braces hold expressions. f"score: {x}" interpolates x at the brace position. The expression inside the braces can be anything Python can evaluate, including arithmetic, function calls, and attribute access.

The optional format spec after a colon controls how a value is rendered. f"{pi:.2f}" formats pi to two decimal places. The full format spec language is fiddly but a handful of common cases (decimals, padding, percentages) are easy to memorize.

F-strings are the modern way to interpolate. The older % and .format() styles still work but read worse and offer nothing extra. Reach for an f-string by default and only switch when you have a specific reason.

python
name, score = "Ada", 92
f"{name}: {score}"          # 'Ada: 92'
f"double = {score * 2}"     # 'double = 184'
f"pi = {3.14159:.2f}"        # 'pi = 3.14'
← PREVIOUS
Operators and Expressions
NEXT →
Input and Output