Python — Parsing text with str.partition
Python str.partition returns the text before a separator, the separator itself and the remaining text. An empty middle field means the separator was absent.
A simple example
Split one line of text
- Start with "a=b"
- Do this Separate at =
- Result b
parts = "a=b".split("=")
print(parts[1])
b
Split one setting into a key and a value
partition always returns three strings. The middle string is empty when the separator is absent. strip removes surrounding whitespace and leaves internal spaces intact.
A noticeboard reads its city from a saved setting. Split the line at its first equals sign and trim the spaces around the two fields. The board can now look up city and display Lima.
Run the example
Python 3.8 or later. Run these commands from the directory containing the example.
python3 lesson.py
record = " city = Lima "
key, separator, value = record.partition("=")
if separator:
print(f"{key.strip()}={value.strip()}")
city=Lima
The input contains padding around city and Lima. Locating the first separator identifies the two fields. Trimming their ends gives city=Lima without changing text inside the value.
Try it yourself
What should city = A=B produce?
Check your answer
The value retains its second equals sign. The normalized line is city=A=B. Decide separately whether an empty key is valid for your file format.