Use regular expressions (re
module):
>>> import re
>>> match = re.search('(\d+) ooo(\w+)', '12 ooops')
>>> match.group(1), match.group(2)
('12', 'ps')
Regular expressions is as near as you can get to do what you want. There is no way to do it using the same format string ('%d ooo%s'
).
EDIT: As @Daenyth suggested, you could implement your own function with this behaviour:
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")
Usage:
>>> 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
Of course, python_scanf
won't work with more complex patterns like %.4f
or %r
.