CodeBlanks Logo Icon CodeBlanks

Summary - Advanced strings

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

main.py
# split, strip and replace together

Sample solution

main.py
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

main.py
# Find the extension with split

Sample solution

main.py
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

Question
result = ",".____(["a", "b", "c"])
Answer
result = ",".join(["a", "b", "c"])

Explanation: The list combining method is join.

All lessons in Beginner