Python · Lesson 3 of 15
Working with Strings
Indexing, slicing, the everyday string methods and clean formatting with f-strings.
- Beginner
- 14 min read
- 3 objectives
Before this lessonLesson 2: Variables and Types
What you will learn
- Slice and index text
- Use split, join, strip and replace
- Format numbers with f-strings
Text is everywhere in real programs: names, emails, log lines, file paths, API responses. A Python str is an immutable sequence of characters. Sequence means you can index and slice it like a list. Immutable means no operation changes a string in place; every method returns a new string and leaves the original alone.
Creating strings
Use single or double quotes, whichever avoids escaping. Triple quotes span several lines. A backslash starts an escape sequence such as \n (new line) or \t (tab). Prefix a string with r to keep backslashes literal, which is handy for Windows paths and regular expressions.
single = 'It is fine'
double = "She said \"hi\""
poem = """Roses are red,
Violets are blue"""
path = r"C:\new\table"
print(single)
print(double)
print(poem)
print(path)It is fine She said "hi" Roses are red, Violets are blue C:\new\table
Indexing and slicing
Each character has a position starting at 0. Negative positions count from the end, so -1 is the last character. A slice text[start:stop] takes characters from start up to but not including stop. Leave either side empty to go to that end, and add a third number as the step.
word = "stackcone"
print(word[0], word[-1])
print(word[0:5])
print(word[5:])
print(word[::-1])
print(word[::2])
print(len(word))s e stack cone enockcats sakoe 9
Everyday string methods
Methods are functions attached to a value, called with a dot. The ones you will use constantly clean up text (strip, lower), search it (startswith, find, in) and rewrite it (replace).
raw = " Hello, World! "
clean = raw.strip()
print(clean)
print(clean.lower(), clean.upper())
print(clean.replace("World", "Python"))
print(clean.startswith("Hello"), clean.endswith("?"))
print("World" in clean)
print(clean.find("o"), clean.count("l"))
print(raw)Hello, World! hello, world! HELLO, WORLD! Hello, Python! True False True 4 3 Hello, World!
Notice the last line: raw is unchanged, because strip() returned a new string.
Splitting and joining
split() turns a string into a list of pieces, and join() glues a list back into one string. Together they handle most text-processing chores, such as reading comma-separated values or building a sentence. Note the odd-looking order of join: you call it on the separator.
line = "ada,grace,linus"
names = line.split(",")
print(names)
print(" & ".join(names))
print("one two three".split())
print("-".join(["2026", "01", "15"]))['ada', 'grace', 'linus'] ada & grace & linus ['one', 'two', 'three'] 2026-01-15
Formatting with f-strings
An f-string embeds expressions inside braces. After a colon you can control the format: number of decimals, thousands separators, alignment and padding. This is the modern, readable replacement for + concatenation and % formatting.
name = "Ada"
score = 93.456
big = 1234567
print(f"{name} scored {score:.1f}")
print(f"Population: {big:,}")
print(f"{name:>8}|{name:<8}|{name:^8}|")
print(f"{7:03d}")
print(f"{0.256:.0%}")
print(f"{name!r}")Ada scored 93.5
Population: 1,234,567
Ada|Ada | Ada |
007
26%
'Ada'Checking what a string contains
Methods such as isdigit(), isalpha() and isspace() answer yes/no questions about the characters, which is a cheap way to validate input before converting it.
for text in ["2026", "abc", "12a", ""]:
print(repr(text), text.isdigit(), text.isalpha())'2026' True False 'abc' False True '12a' False False '' False False
Common mistakes
- Expecting in-place changes:
s.upper()on its own does nothing useful. Assign the result:s = s.upper(). - Assigning to an index:
s[0] = "X"raisesTypeErrorbecause strings are immutable. Build a new string with slicing orreplace. - Joining non-strings:
",".join([1, 2])fails. Convert first:",".join(str(n) for n in nums). - Off-by-one slices: the stop index is excluded, so
s[0:3]has three characters, not four.
# Write your solution here
