Split a string only by first space in python

PythonStringSplit

Python Problem Overview


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?

Python Solutions


Solution 1 - Python

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

>>> s = "238 NEO Sports"
>>> s.split(" ", 1)
['238', 'NEO Sports']

Solution 2 - Python

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

>>> "238 NEO Sports".split(None, 1)
['238', 'NEO Sports']

Solution 3 - Python

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

Solution 4 - Python

Use string.split()

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

Output:

['238', 'NEO Sports']

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionbazingaView Question on Stackoverflow
Solution 1 - PythonAvinash RajView Answer on Stackoverflow
Solution 2 - PythonwimView Answer on Stackoverflow
Solution 3 - PythonShubham GuptaView Answer on Stackoverflow
Solution 4 - PythonHaresh ShyaraView Answer on Stackoverflow