85

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
  • 14,712
  • 2
  • 33
  • 62
bazinga
  • 1,930
  • 4
  • 19
  • 33

4 Answers4

155

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

>>> s = "238 NEO Sports"
>>> s.split(" ", 1)
['238', 'NEO Sports']
Avinash Raj
  • 166,785
  • 24
  • 204
  • 249
37

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

>>> "238 NEO Sports".split(None, 1)
['238', 'NEO Sports']
wim
  • 302,178
  • 90
  • 548
  • 690
  • 11
    This is the only answer which works with any whitespace such as tabs. +1 – PolyMesh Nov 16 '17 at 00:46
  • 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
3

**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)
2

Use string.split()

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

Output:

['238', 'NEO Sports']
Haresh Shyara
  • 1,578
  • 9
  • 13