Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split a string only by first space in python

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?

like image 865
bazinga Avatar asked Jun 04 '15 06:06

bazinga


People also ask

How do you split the first part of a string in Python?

Use the str. split() method with maxsplit set to 1 to split a string and get the first element, e.g. my_str. split('_', 1)[0] .

How do you split a string into the first space?

Using the split() Method For example, if we put the limit as n (n >0), it means that the pattern will be applied at most n-1 times. Here, we'll be using space (” “) as a regular expression to split the String on the first occurrence of space.

How do you split a string by space in Python?

The split() method splits a string into a list. You can specify the separator, default separator is any whitespace. Note: When maxsplit is specified, the list will contain the specified number of elements plus one.

How do you split the first comma in Python?

You can use the Python string split() function to split a string (by a delimiter) into a list of strings. To split a string by comma in Python, pass the comma character "," as a delimiter to the split() function. It returns a list of strings resulting from splitting the original string on the occurrences of "," .


1 Answers

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

>>> s = "238 NEO Sports" >>> s.split(" ", 1) ['238', 'NEO Sports'] 
like image 99
Avinash Raj Avatar answered Sep 23 '22 17:09

Avinash Raj