Split based by a-z character in an alphanumeric string in python
I have strings like "5d开发者_C百科4h2s", where I want to get 5, 4, and 2 from that string, but I also want to know that 5 was paired with d, and that 4 was paired with h, etc etc. Is there an easy way of doing this without parsing char by char?
If your input does not get more complicated than 5d4h2s
:
>>> import re
>>> s = "5d4h2s"
>>> p = re.compile("([0-9])([a-z])")
>>> for m in p.findall(s):
... print m
...
('5', 'd')
('4', 'h')
('2', 's')
And if it gets, you can easily adjust the regular expression, e.g.
>>> p = re.compile("([0-9]*)([a-z])")
to accept input like:
>>> s = "5d14h2s"
Finally, you can condense the regex to:
>>> p = re.compile("([\d]+)([dhms])")
For time string, you can try the following:
m = re.match("(\d+d)?(\d+h)?(\d+m)?(\d+s)?", "5d4h2s")
print m.group(1) # Days
print m.group(2) # Hours
print m.group(3) # Minutes
print m.group(4) # Seconds
print int(m.group(1)[:-1]) # Days, number
精彩评论