使用以下测试脚本:import re
def string(s):
return '{}.{}'.format(s[:2], s[2:])
def regex(s):
return re.sub(r'^(d{2})', r'1.', s)
def numerical(s):
return str(int(s) / (10 ** (len(s) - 2)))
if __name__ == '__main__':
from textwrap import dedent
from timeit import timeit
funcs = ('string', 'regex', 'numerical')
test = '{}(s)'
setup = dedent('''
from __main__ import {}
s = "2276514"
assert {}
'''.format(
', '.join(funcs),
' == '.join(test.format(func) for func in funcs),
)
)
for func in funcs:
print(func, timeit(test.format(func), setup=setup))
结果发现,使用正则表达式比做数学运算或只是对字符串切片效率要低得多:
^{pr2}$
如果您真的想要这个数字(即,将float添加到前两个,并从最后一个中删除{}),那么数值方法是最快的:string 1.449586457505659
regex 9.255363527420872
numerical 0.9225037999760559
不管怎样,regex都会失败;您可以通过预编译模式来节省一点时间(例如,将pattern=re.compile(r'^(d{2})')作为默认参数,并在函数中使用pattern.sub(r'1.', s)),但这还不足以产生影响。在
最后
以上就是烂漫荷花最近收集整理的关于python正则获取字符串的前七个字符_在字符串的前两个字符后插入“.”的Python正则表达式...的全部内容,更多相关python正则获取字符串内容请搜索靠谱客的其他文章。
发表评论 取消回复