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"
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.
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 "," .
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.
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.
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]
>>> s = "123mango abcd mango kiwi peach" >>> s.split("mango", 1) ['123', ' abcd mango kiwi peach'] >>> s.split("mango", 1)[1] ' abcd mango kiwi peach'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With