Python strip()多个字符?


75

我想从字符串中删除任何括号。为什么这不能正常工作?

>>> name = "Barack (of Washington)"
>>> name = name.strip("(){}<>")
>>> print name
Barack (of Washington

Answers:


61

我在这里进行了一次时间测试,每种方法循环使用了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它不是最易读的内容。其他三个更为明显,尽管程度有所不同。


2
感谢这个有教育意义的问题,我不仅学会了strip()不能达到我的预期,而且还学习了三种其他方式来实现自己想要的目标,并且这是最快的!
AP257

1
不适用于unicode:translate()仅使用unicode的一个参数(表)。
富裕

15
负1:用于提高速度,这应该与代码的清晰度和健壮性有关。
jwg

@jwg,你完全正确;回顾这一点,这是一个高清晰性的练习。但是,无论如何,它一直在投票。(不过,我确实学过一些有关使用timeit的有趣知识。)
JasonFruit

97

因为那不是什么strip()。它删除参数中存在的前导和尾随字符,但不删除字符串中间的那些字符。

您可以这样做:

name= name.replace('(', '').replace(')', '').replace ...

要么:

name= ''.join(c for c in name if c not in '(){}<>')

或使用正则表达式:

import re
name= re.sub('[(){}<>]', '', name)

18

string.translate with table = None不能正常工作。

>>> name = "Barack (of Washington)"
>>> name = name.translate(None, "(){}<>")
>>> print name
Barack of Washington

12
这在Python 3中不适用于字符串,仅适用于字节和字节数组。
马克·劳伦斯

14

因为strip()仅根据您提供的内容去除尾随和前导字符。我建议:

>>> import re
>>> name = "Barack (of Washington)"
>>> name = re.sub('[\(\)\{\}<>]', '', name)
>>> print(name)
Barack of Washington

4
在正则表达式字符类,你不需要逃避什么,所以“[(){} <>]”是好的
麦克Axiak

8

strip 仅从字符串的最前面和后面去除字符。

要删除字符列表,可以使用字符串的translate方法:

import string
name = "Barack (of Washington)"
table = string.maketrans( '', '', )
print name.translate(table,"(){}<>")
# Barack of Washington

-4

例如字符串 s="(U+007c)"

要仅删除s中的括号,请尝试以下方法:

import re
a=re.sub("\\(","",s)
b=re.sub("\\)","",a)
print(b)

如何去除括号?通过删除不是字母数字的任何内容?
杰夫·谢勒

当问题说“删除括号”但您的回答是“删除不是字母数字的所有内容”时,我认为您没有解决这个问题。
杰夫·谢勒
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.