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?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
Just pass the count as second parameter to str.split function.
>>> s = "238 NEO Sports"
>>> s.split(" ", 1)
['238', 'NEO Sports']
Method 2
RTFM: str.split(sep=None, maxsplit=-1)
>>> "238 NEO Sports".split(None, 1) ['238', 'NEO Sports']
Method 3
Use string.split()
string = "238 NEO Sports"
print string.split(' ', 1)
Output:
['238', 'NEO Sports']
Method 4
**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)
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0