删除Python中用点分隔的字符串的最后一部分 [英] Remove the last part of string separated with dot in Python
本文介绍了删除Python中用点分隔的字符串的最后一部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何以优雅的方式转换字符串,例如:
'test.test1.test2''test.test3.test4'
变成这样的字符串:
'test.test1''test.test3'
解决方案
这里不需要正则表达式.
使用 str.rsplit()
:
output = inputstr.rsplit('.', 1)[0]
output = inputstr.rpartition('.')[0]
str.rpartition()
是两者中速度更快的,但您需要 Python 2.5 或更新版本.
演示:
<预><代码>>>>'test.test1.test2'.rsplit('.', 1)[0]'test.test1'>>>'test.test1.test2'.rpartition('.')[0]'test.test1'>>>'test.test3.test4'.rsplit('.', 1)[0]'test.test3'>>>'test.test3.test4'.rpartition('.')[0]'test.test3'与一百万次运行的时间比较:
<预><代码>>>>从时间导入时间>>>timeit("s.rsplit('.', 1)[0]", "s = 'test.test1.test2'")0.5848979949951172>>>timeit("s.rpartition('.')[0]", "s = 'test.test1.test2'")0.27417516708374023您可以以 100 万次 str.rsplit()
的价格运行 200 万次 str.rpartition()
调用.
How is it possible to convert in elegant way strings like:
'test.test1.test2'
'test.test3.test4'
into strings like these:
'test.test1'
'test.test3'
解决方案
No need for regular expressions here.
Use str.rsplit()
:
output = inputstr.rsplit('.', 1)[0]
or str.rpartition()
:
output = inputstr.rpartition('.')[0]
str.rpartition()
is the faster of the two but you need Python 2.5 or newer for it.
Demo:
>>> 'test.test1.test2'.rsplit('.', 1)[0]
'test.test1'
>>> 'test.test1.test2'.rpartition('.')[0]
'test.test1'
>>> 'test.test3.test4'.rsplit('.', 1)[0]
'test.test3'
>>> 'test.test3.test4'.rpartition('.')[0]
'test.test3'
And a time comparison against a million runs:
>>> from timeit import timeit
>>> timeit("s.rsplit('.', 1)[0]", "s = 'test.test1.test2'")
0.5848979949951172
>>> timeit("s.rpartition('.')[0]", "s = 'test.test1.test2'")
0.27417516708374023
where you can run 2 million str.rpartition()
calls for the price of 1 million str.rsplit()
's.
这篇关于删除Python中用点分隔的字符串的最后一部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文