我有类似“ 5d4h2s”的字符串,我想从该字符串中获取5、4和2,但我也想知道5与d配对,而4与h配对,依此类推。等等。一个简单的方法,而无需通过char解析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, eg
>>> 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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.