96

I have string for example: "238 NEO Sports". I want to split this string only at the first space. The output should be ["238","NEO Sports"].

One way I could think of is by using split() and finally merging the last two strings returned. Is there a better way?

Ma0
  • 15,057
  • 4
  • 35
  • 65
bazinga
  • 2,120
  • 4
  • 21
  • 35

4 Answers4

177

Just pass the count as second parameter to str.split function.

>>> s = "238 NEO Sports"
>>> s.split(" ", 1)
['238', 'NEO Sports']
Avinash Raj
  • 172,303
  • 28
  • 230
  • 274
38

RTFM: str.split(sep=None, maxsplit=-1)

>>> "238 NEO Sports".split(None, 1)
['238', 'NEO Sports']
wim
  • 338,267
  • 99
  • 616
  • 750
  • 11
    This is the only answer which works with any whitespace such as tabs. +1 – PolyMesh Nov 16 '17 at 00:46
  • 1
    I think it is really a bad style to supply an argument set to its default value just to move to the next argument which is directly accessible as a keyword argument. Much better answer by Shubham Gupta: `"238 NEO Sports".split(maxsplit=1)` – pabouk - Ukraine stay strong May 17 '22 at 14:36
  • 1
    @pabouk Normally I'd agree, but the downside of that is it only works on Python 3.3+. If you want to write a cross-compatible code which works on Python 2 + Python 3 the same way, you have to do it like this. Do note the answer is from 7 years ago.. – wim May 17 '22 at 16:50
5

**Use in-built terminology, as it will helpful to remember for future reference. When in doubt always prefer string.split(shift+tab)

string.split(maxsplit = 1)
Shubham Gupta
  • 57
  • 1
  • 6
3

Use string.split()

string = "238 NEO Sports"
print string.split(' ', 1)

Output:

['238', 'NEO Sports']
Haresh Shyara
  • 1,826
  • 10
  • 13