Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Splitting on first occurrence

Tags:

python

split

What would be the best way to split a string on the first occurrence of a delimiter?

For example:

"123mango abcd mango kiwi peach" 

splitting on the first mango to get:

"abcd mango kiwi peach" 
like image 762
Acorn Avatar asked Aug 01 '11 19:08

Acorn


People also ask

How do I split a string with 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 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 "," .

How do you split a string into the right in Python?

Python String rsplit() Method The rsplit() method splits a string into a list, starting from the right. If no "max" is specified, this method will return the same as the split() method. Note: When maxsplit is specified, the list will contain the specified number of elements plus one.

What is Maxsplit in Python?

maxsplit : It is a number, which tells us to split the string into maximum of provided number of times. If it is not provided then the default is -1 that means there is no limit. Returns : Returns a list of strings after breaking the given string by the specified separator.


2 Answers

From the docs:

str.split([sep[, maxsplit]])

Return a list of the words in the string, using sep as the delimiter string. If maxsplit is given, at most maxsplit splits are done (thus, the list will have at most maxsplit+1 elements).

s.split('mango', 1)[1] 
like image 84
Ignacio Vazquez-Abrams Avatar answered Sep 19 '22 03:09

Ignacio Vazquez-Abrams


>>> s = "123mango abcd mango kiwi peach" >>> s.split("mango", 1) ['123', ' abcd mango kiwi peach'] >>> s.split("mango", 1)[1] ' abcd mango kiwi peach' 
like image 36
utdemir Avatar answered Sep 22 '22 03:09

utdemir