PythiloLesson 9 of 30 · progress kept in this browser

String methods

Strings have many methods, and none of them change the string. Each returns a new value, so keep the result.

s = "  Hello, World  "
t = s.strip()
print(t.lower())             # hello, world
print(t.replace("World", "Ada"))
print(t.startswith("Hell"))  # True
print(t.find("o"), t.count("o"))  # 4 2
print("42".isdigit(), "4a".isdigit())
print("x" in t)              # False
print("k=v=w".partition("="))
  • find returns the position of the first match, or -1. index does the same but raises ValueError when nothing matches.
  • count counts matches that do not overlap.
  • isdigit, isalpha and isspace are true only when every character fits.
  • split(",") splits at every comma and keeps empty pieces.
  • partition("=") splits once, at the first match, and returns three parts: before, the separator, after. If there is no match, the last two are empty.

A line like s.upper() on its own does nothing useful. Write s = s.upper().

Your task

Write parse_setting(line) that turns text like " Volume = 7 " into ("volume", "7"): split at the first =, strip both parts, lower-case the key, and return None if there is no =. Write digits_only(text) returning just the digit characters of text.

Next: Loops