[英]Python strip() multiple characters?
我想从字符串中删除任何括号。 为什么这不能正常工作?
>>> name = "Barack (of Washington)"
>>> name = name.strip("(){}<>")
>>> print name
Barack (of Washington
因为这不是strip()
所做的。 它删除参数中存在的前导和尾随字符,但不会删除字符串中间的那些字符。
你可以这样做:
name= name.replace('(', '').replace(')', '').replace ...
或:
name= ''.join(c for c in name if c not in '(){}<>')
或者使用正则表达式:
import re
name= re.sub('[(){}<>]', '', name)
我在这里做了一个时间测试,每个方法循环使用 100000 次。 结果令我吃惊。 (针对评论中的有效批评对其进行编辑后,结果仍然让我感到惊讶。)
这是脚本:
import timeit
bad_chars = '(){}<>'
setup = """import re
import string
s = 'Barack (of Washington)'
bad_chars = '(){}<>'
rgx = re.compile('[%s]' % bad_chars)"""
timer = timeit.Timer('o = "".join(c for c in s if c not in bad_chars)', setup=setup)
print "List comprehension: ", timer.timeit(100000)
timer = timeit.Timer("o= rgx.sub('', s)", setup=setup)
print "Regular expression: ", timer.timeit(100000)
timer = timeit.Timer('for c in bad_chars: s = s.replace(c, "")', setup=setup)
print "Replace in loop: ", timer.timeit(100000)
timer = timeit.Timer('s.translate(string.maketrans("", "", ), bad_chars)', setup=setup)
print "string.translate: ", timer.timeit(100000)
结果如下:
List comprehension: 0.631745100021
Regular expression: 0.155561923981
Replace in loop: 0.235936164856
string.translate: 0.0965719223022
其他运行的结果遵循类似的模式。 但是,如果速度不是主要问题,我仍然认为string.translate
不是最易读的; 其他三个比较明显,虽然有不同程度的慢。
string.translate with table=None 工作正常。
>>> name = "Barack (of Washington)"
>>> name = name.translate(None, "(){}<>")
>>> print name
Barack of Washington
因为strip()
仅根据您提供的内容去除尾随和前导字符。 我建议:
>>> import re
>>> name = "Barack (of Washington)"
>>> name = re.sub('[\(\)\{\}<>]', '', name)
>>> print(name)
Barack of Washington
strip
只从字符串的最前面和后面去除字符。
要删除字符列表,您可以使用字符串的translate
方法:
import string
name = "Barack (of Washington)"
table = string.maketrans( '', '', )
print name.translate(table,"(){}<>")
# Barack of Washington
例如字符串s="(U+007c)"
要仅删除 s 中的括号,请尝试以下方法:
import re
a=re.sub("\\(","",s)
b=re.sub("\\)","",a)
print(b)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.