Python中是否有任何方法可以反转通过"%"运算符完成的格式化操作?
formated = "%d ooo%s" % (12, "ps")
#formated is now '12 ooops'
(arg1, arg2) = theFunctionImSeeking("12 ooops", "%d ooo%s")
#arg1 is 12 and arg2 is "ps"
Run Code Online (Sandbox Code Playgroud)
编辑 Regexp可以解决这个问题,但是它们更难写,我怀疑它们更慢,因为它们可以处理更复杂的结构.我真的很喜欢sscanf.
使用正则表达式(re模块):
>>> import re
>>> match = re.search('(\d+) ooo(\w+)', '12 ooops')
>>> match.group(1), match.group(2)
('12', 'ps')
Run Code Online (Sandbox Code Playgroud)
正则表达式就像你可以做你想做的那样近.没有办法使用相同的格式字符串('%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")
Run Code Online (Sandbox Code Playgroud)
用法:
>>> 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
Run Code Online (Sandbox Code Playgroud)
当然,python_scanf不会使用像%.4f或更复杂的模式%r.
| 归档时间: |
|
| 查看次数: |
219 次 |
| 最近记录: |