Python theorytheory 0/50 · 0%
Strings · easy

18. String formatting and parsing

f-strings, .format(), split/join, and number bases.

Beyond f-strings, `.format()` and `%`-formatting exist for legacy code, but f-strings are preferred for new code.

python
addr = "0x" + "ab" * 2
parts = "a,b,c".split(",")          # ["a", "b", "c"]
",".join(["a", "b", "c"])           # "a,b,c"
int("ff", 16)                        # 255, parse hex
hex(255)                             # "0xff"
f"{3.14159:.2f}"                     # "3.14"

`str.strip()`, `.lstrip()`, `.rstrip()` remove whitespace (or given characters) from ends, useful for cleaning user input before validation.

Check your understanding

  1. 1. What does `"a,b,c".split(",")` return?

  2. 2. What does `int("ff", 16)` return?

  3. 3. What does `f"{3.14159:.2f}"` produce?