正則表達式來拯救!
>>> import re
>>> minsec = re.compile(r'(?P<minutes>\d+)m(?P<seconds>\d+)s')
>>> result = minsec.match('1m30s')
>>> result.groupdict()
{'seconds': '30', 'minutes': '1'}
編輯:這裏是一個修改後的解決方案:
import re
pattern = r'(?:(?P<minutes>\d+)m)?(?:(?P<seconds>\d+)s)?'
minsec = re.compile(pattern)
def parse(s, pat=minsec):
return pat.match(s).groupdict()
tests = ['1m30s', '30s', '10m29s']
for t in tests:
print '---'
print ' in:', t
print 'out:', parse(t)
輸出:
---
in: 1m30s
out: {'seconds': '30', 'minutes': '1'}
---
in: 30s
out: {'seconds': '30', 'minutes': None}
---
in: 10m29s
out: {'seconds': '29', 'minutes': '10'}
我太慢了。你贏了。 – nmichaels 2010-09-09 20:40:15