[英]What is the fastest way to filter a set of substrings from a string in python?
I'm looking at a statement that looks like this: 我正在看一个看起来像这样的语句:
def fn(somelongstring):
shorterstring = somelongstring.replace('very, ','').replace('long ', '')
fn('some very, very, very, long string')
what's the most efficient method for performing this kind of operation in Python? 在Python中执行这种操作的最有效方法是什么?
Some notes: 一些注意事项:
Use an re: 使用重新:
import re
shorterstring = re.sub('very, |long ', '', 'some very, very, very, long string')
You'll need to make sure that the substrings to replace with nothing are in descending order of length so that longer matches are replaced first. 您需要确保不替换任何内容的子字符串按长度降序排列,以便较长的匹配项首先被替换。
Or, you could avoid the chained calls, and use: 或者,您可以避免链式调用,并使用:
reduce(lambda a, b: a.replace(b, ''), ['very, ', 'long '], s)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.