使用正则表达式(re
模块):
>>> import re
>>> match = re.search('(\d+) ooo(\w+)', '12 ooops')
>>> match.group(1), match.group(2)
('12', 'ps')
正则表达式是尽可能接近你可以得到你想要的东西。没有办法使用相同的格式字符串('%d ooo%s'
)。
编辑:作为@Daenyth建议,你可以实现这种行为自己的函数:
import re
def python_scanf(my_str, pattern):
D = ('%d', '(\d+?)')
F = ('%f', '(\d+\.\d+?)')
S = ('%s', '(.+?)')
re_pattern = pattern.replace(*D).replace(*F).replace(*S)
match = re.match(re_pattern, my_str)
if match:
return match.groups()
raise ValueError("String doesn't match pattern")
用法:
>>> python_scanf("12 ooops", "%d ooo%s")
('12', 'p')
>>> python_scanf("12 ooops", "%d uuu%s")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 10, in python_scanf
ValueError: String doesn't match pattern
当然,python_scanf
不会更复杂的工作如%.4f
或%r
。
是:使用正则表达式。 – Marcin 2012-01-31 17:58:00
可能重复的[sscanf在Python](http://stackoverflow.com/questions/2175080/sscanf-in-python) – 2012-01-31 17:59:39
@MichaelMrozek谢谢,我忘了那个C函数的名称 – AsTeR 2012-01-31 18:01:51