I’m trying to split a string into an initial numeric component and the remaining components, using the first occurrence of a letter as the delimiter, so for example:
"123b" -> ["123", "b"]
"12b7.97ap" -> ["12", "b7.97ap"]
I’m new to regex and I’m having trouble achieving this… The best I could do is:
re.split(r"(\d+)", string)
But this returns:
["", "123", "b"]
["", "12", "b", "7", ".", "97", "ap"]
For the two examples above. I suppose I could then combine all the elements after index 1 into a single string, but I’m sure there’s a better way… Thanks in advance for any help!
>Solution :
One possibility, first matching digits and then matching the rest:
import re
for s in "123b", "12b7.97ap":
print(re.findall('\d+|.+', s))
Output:
['123', 'b']
['12', 'b7.97ap']