How to get the first word in the string

Regex is unnecessary for this. Just use some_string.split(' ', 1)[0] or some_string.partition(' ')[0].


If you want to feel especially sly, you can write it as this:

(firstWord, rest) = yourLine.split(maxsplit=1)

This is supposed to bring the best from both worlds:

  • optimality tweak with maxsplit while splitting with any whitespace
  • improved reliability and readability, as argued by the author of the technique.

I kind of fell in love with this solution and it's general unpacking capability, so I had to share it.