← Python from Scratch
Lesson 14 of 78 · 10 XP
String methods
Theory and problem statement
Machine translation, not yet reviewed by a native speaker.
A method is a function that "belongs" to a value and is called with a dot. Strings have lots of them:
s = " Hello, World "
s.strip() # 'Hello, World' — remove spaces at the edges
s.lower() # ' hello, world '
s.upper() # ' HELLO, WORLD '
s.replace("World", "IGD") # ' Hello, IGD '
"a,b,c".split(",") # ['a', 'b', 'c'] — cut into a list
"one two three".split() # ['one', 'two', 'three'] — splits on any whitespace
"-".join(["a", "b", "c"]) # 'a-b-c' — join a list
"banana".count("a") # 3
"banana".find("n") # 2 — index of the first occurrence, or -1
Methods don't change the original string; they return a new one. You can chain them:
" HeLlO ".strip().lower() # 'hello'
Task. Write a function normalize(s) that tidies a string up: removes spaces at the edges, collapses several spaces in a row into one, and makes all letters lowercase. normalize(" Hello WORLD ") → 'hello world'.
Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.