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?
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] .
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.
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.
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 "," .
Just pass the count as second parameter to str.split
function.
>>> s = "238 NEO Sports" >>> s.split(" ", 1) ['238', 'NEO Sports']
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