Search GimmeJob

Type at least 2 characters. Enter also searches by meaning.
Python interview question
Strings & text processingJuniorVery commonPractical

What do `strip()`, `split()` and `join()` do, and what is a common mistake with `split()`'s default behavior?

Answer

`strip()` removes leading and trailing whitespace (or a given set of characters) without touching the middle of the string. `split()` breaks a string into a list on a separator, and with no argument at all it splits on any run of whitespace and discards empty strings from leading/trailing/repeated separators, which surprises people who expect a plain single-space split. `join()` is the inverse of `split()`: it is called on the separator string and stitches an iterable of strings together with that separator between each piece.

Strong answer includes

  • strip trims edges, not the interior
  • split() with no argument splits on any whitespace run and drops empty pieces
  • join is called on the separator, not the list

Practical example

Python example
"  a   b  c ".split()

returns

Python example
['a', 'b', 'c']

, cleanly collapsing all whitespace, while

Python example
"  a   b  c ".split(" ")

returns

Python example
['', '', 'a', '', '', 'b', 'c', '']

, keeping every empty gap.

#strings#gotchas

Sources

The Python Standard LibraryPython Software Foundation · Authoritative behavior for built-in types and standard library modules