How does str.split() with no argument differ from str.split(' ')?
answer
- One of the two forms collapses runs
- Watch what happens to empty fields
- Try both on the empty string
- Whitespace mode versus exact-separator mode
- partition always returns three elements
basics
~20 sWith no argument, str.split treats any run of whitespace as one separator and discards leading and trailing whitespace, so it never yields empty strings. With ' ' it splits on each single space, so runs of spaces produce empty strings.
solid answer
~40 s`str.split()` with no argument runs a special whitespace mode: consecutive whitespace of any kind — spaces, tabs, newlines — counts as **one** separator, and leading and trailing whitespace is discarded, so the result never contains an empty string. `' a b '.split()` gives `['a', 'b']`. Passing an explicit separator switches to exact mode: every single occurrence delimits a field, so `' a b '.split(' ')` gives `['', '', 'a', '', 'b', '', '']`. The empty string shows the split most sharply: `''.split()` is `[]` while `''.split(',')` is `['']`. Use the no-argument form to tokenise free text, and an explicit separator for structured data where an empty field is meaningful. `maxsplit` caps the number of splits, `str.rsplit` counts from the right, and `str.partition` returns a fixed three-tuple that never needs an unpacking guard.
code
pycon · 8 lines>>> ' a b '.split()
['a', 'b']
>>> ' a b '.split(' ')
['', '', 'a', '', 'b', '', '']
>>> ''.split()
[]
>>> ''.split(',')
['']go deeper
Know that calling the method with no argument splits on any run of whitespace and trims the ends, while passing a separator splits on every single occurrence. Try both on a string with double spaces until the difference sticks.
Explain the two modes as genuinely different behaviours, use the empty string as your proof case, and know maxsplit and the right-hand variant. Be able to say which mode a delimited feed needs and why the other corrupts records.
Demonstrate the failure mode: whitespace-splitting a delimited record collapses empty columns and shifts every later field, producing wrong data rather than an exception. Reach for the three-tuple partition method in parsing code so malformed input is detected, not unpacked.
Frame it as a parsing-contract decision: hand-rolled splitting is fine for a fixed internal format and wrong for anything with quoting or escaping, where a real parser from the standard library belongs. Set the boundary for the team rather than reviewing each call.
### Two methods wearing one name `str.split` has two genuinely different behaviours depending on whether you pass a separator, and the difference is not a detail — it changes the length of the result. **No argument (or `None`): whitespace mode.** Any *run* of whitespace acts as a single separator, and whitespace at the start and end of the string is ignored entirely. Whitespace here means spaces, tabs, newlines, carriage returns, form feeds, vertical tabs and the other characters Unicode calls whitespace — you are not limited to the ASCII space. The result can never contain an empty string. **An explicit separator: exact mode.** Every single occurrence of the separator delimits a field, adjacent separators produce empty fields, and a leading or trailing separator produces an empty field at that end. The separator may be several characters long and is matched as an exact substring; passing `''` raises `ValueError`. ```python ' a b '.split() # ['a', 'b'] ' a b '.split(' ') # ['', '', 'a', '', 'b', '', ''] 'a\t\nb'.split() # ['a', 'b'] 'a,,b'.split(',') # ['a', '', 'b'] ``` The empty string is the cleanest illustration of the split in semantics: `''.split()` returns `[]` — there were no tokens — while `''.split(',')` returns `['']` — there was one field and it was empty. Code that assumes a non-empty list after splitting a possibly-empty line is relying on which of the two it called. ### Choosing between them The rule follows from what an empty field *means* in your data. - **Free text, human-entered, ragged spacing** — command output, a log line, a pasted description. Use `split()`. Runs of spaces are noise, and collapsing them is the behaviour you want. - **Structured records where position matters** — a delimited feed, a config line, anything where a missing value is still a value. Use an explicit separator. `'1120,,blue'` must yield three fields, the middle one empty; whitespace mode would silently reshape the record. Getting this backwards is a real defect in an ingest path: splitting a delimited record on whitespace silently merges empty columns and shifts every later field left by one, which then lands in the wrong column downstream rather than raising anything. ### `maxsplit`, `rsplit`, and `splitlines` `maxsplit` caps how many splits happen; the remainder stays whole in the last element. `'a=b=c'.split('=', 1)` gives `['a', 'b=c']` — exactly right for a `key=value` line whose value may itself contain the delimiter. `str.rsplit` is the same method counting from the right, which is how you take the last field: `'a,b,c'.rsplit(',', 1)` gives `['a,b', 'c']`. In whitespace mode `maxsplit` still collapses runs. `str.splitlines` is a separate method for text, not a `split('\n')` alias: it splits on the whole family of line boundaries — `\n`, `\r`, `\r\n` and several Unicode separators — and by default does not leave a trailing empty element for a file ending in a newline. `'a\n'.splitlines()` is `['a']` while `'a\n'.split('\n')` is `['a', '']`. ### `partition` when there is exactly one delimiter `str.partition(sep)` always returns a three-tuple: everything before the first separator, the separator itself, and everything after. When the separator is absent you get `(whole_string, '', '')` — still three elements. That fixed shape is why it beats `split(sep, 1)` for parsing: you can unpack it unconditionally. ```python key, sep, value = line.partition('=') if not sep: raise ValueError(f'missing = in {line!r}') ``` With `split('=', 1)` the same code needs a length check first, because a line without a delimiter yields a one-element list and the unpack raises `ValueError`. `str.rpartition` splits at the **last** occurrence, which is the tool for pulling a trailing segment off an identifier. A subtle point worth having ready: `partition` distinguishes "the separator was present with an empty right-hand side" from "the separator was absent", because `sep` is `'='` in the first case and `''` in the second. A `split`-based parser has to reconstruct that distinction from the list length. ### Interview framing The question is a mechanics probe: an interviewer asking it wants to hear that the no-argument form is a distinct mode, not a default separator of `' '`. Reach for the empty-string case as your proof, then show judgement by naming which mode you would use for a ragged log line versus a delimited record, and mention `partition` as the unpack-safe option for single-delimiter parsing.
- Why prefer str.partition over str.split(sep, 1) when parsing a key=value line?partition always returns a three-tuple, so `key, sep, value = line.partition('=')` never raises on a malformed line — you detect the failure by testing whether sep is empty. split(sep, 1) returns one element when the delimiter is absent, so the same unpack raises ValueError and you need a length check first. partition also distinguishes an absent delimiter from a present one with an empty value; the split-based version has to infer that from the list length.
- How does str.splitlines differ from str.split('\n')?splitlines recognises the whole family of line boundaries — \n, \r, \r\n and several Unicode line separators — and by default does not emit a trailing empty element for text ending in a newline. So 'a\n'.splitlines() is ['a'] while 'a\n'.split('\n') is ['a', '']. Pass keepends=True to retain the terminators. For reading text, splitlines is almost always what you want.
- What happens if you call str.split with an empty separator?It raises ValueError: empty separator. There is no meaningful field boundary between every pair of characters, so the method refuses rather than guessing. If you actually want the individual characters, use list(s) or iterate the string directly — a str is already an iterable of one-character strings.
saying these in an interview costs you the question
- Thinks split() is just shorthand for split(' ')
- Expects ''.split(',') to return an empty list
- Splits a delimited record on whitespace, silently dropping empty fields
- Unpacks split(sep, 1) into two names without a guard
- Believes splitlines is an alias for split('\n')
- Assumes split with an empty separator yields characters