Summary - Advanced strings
- Python course
- Beginner
- Lesson 93/116
- 5 min
Combine split, join and replace to write a CSV parser.
Summary - Advanced string methods
In this group we covered split/join, strip, replace, find/index and startswith/endswith.
- split: splits a string; join: combines a list.
- strip/lstrip/rstrip: removes spaces or characters.
- replace: replaces a substring.
- find: returns position, -1 if missing; index: raises ValueError.
- startswith/endswith: returns bool.
Now two tasks combine these concepts.
Practice split, strip and replace together
Assign " hello-world " to raw. Assign raw.strip() to clean. Assign clean.replace("-", " ") to result. Then print print(result).
Starter code
# split, strip and replace togetherSample solution
raw = " hello-world "
clean = raw.strip()
result = clean.replace("-", " ")
print(result)Expected output
hello world
Practice split and endswith together
Assign "photo.jpg" to filename. Assign filename.split(".") to parts. Assign parts[-1] to ext. Then print print(ext).
Starter code
# Find the extension with splitSample solution
filename = "photo.jpg"
parts = filename.split(".")
ext = parts[-1]
print(ext)Expected output
jpg
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which statement is correct?
- split joins a string
- join splits a string
- find returns -1 if not found Correct answer
- strip modifies the original string
Explanation: find returns -1 when not found (it does not raise ValueError).
2 Combine with join
result = ",".____(["a", "b", "c"])
result = ",".join(["a", "b", "c"])
Explanation: The list combining method is join.