Use str.split to turn a string into a list of substrings. Pass a separator such as ':' to divide structured fields, or omit it to split on any run of spaces, tabs, and newlines. section 3.7 section 6.7
s = 'abc def ghi' #1
s.split(' ') #2
s.split() #3
Compare explicit-space splitting with default whitespace splitting: repeated spaces produce empty fields with a separator, but disappear when split uses its default behavior. section 3.7
Keep these behaviors in mind when choosing a splitting strategy:
- Every invocation returns a list of strings, whose length depends on the number of separators found. section 6.7
- Use maxsplit when the input has a variable-length final field or when unpacking requires a bounded number of results. section 7.7
- Use re.split when several different separators must be recognized; str.split accepts one separator string at a time. section 3.7
- Filter or validate fields before conversion: str.isdigit rejects negative numbers, while try and except can handle int conversion failures. section 8.7
Parsing a calculator expression
Given '3 + 4', unpack the whitespace-separated result with `op, first_s, second_s = to_solve.split()`, convert the operands with int, and dispatch through a dictionary of operations. Use `split(maxsplit=3)` when the final field may contain spaces. section 7.7
Splitting usually begins a transformation pipeline: process the resulting words or fields, append generated values to a list, and use str.join when the final output must become one string. File processing can similarly split each line, update a set of unique words, or extract dictionary fields. section 3.7 section 6.11










