Python strip()多个字符?

AP2*_*257 61 python

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

>>> name = "Barack (of Washington)"
>>> name = name.strip("(){}<>")
>>> print name
Barack (of Washington
Run Code Online (Sandbox Code Playgroud)

bob*_*nce 80

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

你可以这样做:

name= name.replace('(', '').replace(')', '').replace ...
Run Code Online (Sandbox Code Playgroud)

要么:

name= ''.join(c for c in name if c not in '(){}<>')
Run Code Online (Sandbox Code Playgroud)

或者使用正则表达式:

import re
name= re.sub('[(){}<>]', '', name)
Run Code Online (Sandbox Code Playgroud)


Jas*_*uit 49

我在这里进行了一次时间测试,在循环中使用每种方法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)
Run Code Online (Sandbox Code Playgroud)

结果如下:

List comprehension:  0.631745100021
Regular expression:  0.155561923981
Replace in loop:  0.235936164856
string.translate:  0.0965719223022
Run Code Online (Sandbox Code Playgroud)

其他运行的结果遵循类似的模式.但是,如果速度不是主要考虑因素,我仍然认为string.translate最不可读; 其他三个更明显,但程度不同.

  • 减1:用于制作速度方面的内容,这应该与代码清晰度和稳健性有关. (9认同)
  • 感谢这个 - 教育性问题,我不仅了解到 strip() 没有按照我的想法做,我还学到了其他三种方法来实现我想要的,这是最快的! (2认同)

che*_*ish 17

string.translate with table = None工作正常.

>>> name = "Barack (of Washington)"
>>> name = name.translate(None, "(){}<>")
>>> print name
Barack of Washington
Run Code Online (Sandbox Code Playgroud)

  • 这在Python 3中不适用于字符串,仅适用于bytes和bytearray. (4认同)

Rue*_*uel 12

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

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

  • 在正则表达式字符类中,您不需要转义任何内容,因此'[(){} <>]'没问题 (4认同)

unu*_*tbu 8

strip 仅从字符串的正面和背面剥离字符.

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

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