如何在python中删除字符串中字符的所有实例?


73

如何删除此字符串中字符的所有实例?这是我的代码:

def findreplace(char, string):
    place = string.index(char)
    string[place] = ''
    return string

但是,如果运行此命令,将发生以下情况:

>>> findreplace('i', 'it is icy')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 3, in findreplace
TypeError: 'str' object does not support item assignment

为什么是这样?

Answers:


136

字符串在Python中是不可变的,这意味着一旦创建了字符串,就无法更改字符串的内容。如果完全需要更改它,则将使用更改创建一个新的字符串实例。

考虑到这一点,我们有很多方法可以解决此问题

  1. 使用str.replace

    >>> "it is icy".replace("i", "")
    't s cy'
    
  2. 使用str.translate

    >>> "it is icy".translate(None, "i")
    't s cy'
    
  3. 使用正则表达式

    >>> import re
    >>> re.sub(r'i', "", "it is icy")
    't s cy'
    
  4. 使用理解作为过滤器,

    >>> "".join([char for char in "it is icy" if char != "i"])
    't s cy'
    
  5. 使用filter功能

    >>> "".join(filter(lambda char: char != "i", "it is icy"))
    't s cy'
    

时序比较

def findreplace(m_string, char):
    m_string = list(m_string)
    for k in m_string:
        if k == char:
            del(m_string[m_string.index(k)])
    return "".join(m_string)

def replace(m_string, char):
    return m_string.replace("i", "")

def translate(m_string, char):
    return m_string.translate(None, "i")

from timeit import timeit

print timeit("findreplace('it is icy','i')", "from __main__ import findreplace")
print timeit("replace('it is icy','i')", "from __main__ import replace")
print timeit("translate('it is icy','i')", "from __main__ import translate")

结果

1.64474582672
0.29278588295
0.311302900314

str.replacestr.translate方法比接受的答案快8倍和5倍。

注意:对于这种情况,理解方法和过滤器方法预计会更慢,因为它们必须创建列表,然后必须再次遍历以构造字符串。并且re对于单个字符替换来说有点过大。因此,它们都被排除在时序比较之外。


.translate(maketrans('',''))是否与.translate(None)相同?
user217285 '17

可以说,对于更复杂的示例,正​​则表达式可以表现更好,并且很高兴看到。但是,很好的答案!
ThatsAMorais

1
“比接受的答案快8到5倍”,没有接受的答案
whackamadoodle3000


3
>>> x = 'it is icy'.replace('i', '', 1)
>>> x
't is icy'

由于您的代码将仅替换第一个实例,因此我认为这就是您想要的。如果要全部替换,请忽略该1参数。

由于您不能替换字符串本身中的字符,因此必须将其重新分配给变量。(本质上,您必须更新引用而不是修改字符串。)


2

replace()方法将对此起作用。这是有助于从字符串中删除字符的代码。可以说

j_word = 'Stringtoremove'
word = 'String'    

for letter in word:
    if j_word.find(letter) == -1:
        continue
    else:
       # remove matched character
       j_word = j_word.replace(letter, '', 1)

#Output
j_word = "toremove"

1

我建议拆分(不是说其他​​答案无效,这只是另一种方法):

def findreplace(char, string):
   return ''.join(string.split(char))

按字符拆分将删除所有字符并将其变成一个列表。然后,我们使用join函数将列表加入。您可以在下面看到ipython控制台测试

In[112]: findreplace('i', 'it is icy')
Out[112]: 't s cy'

还有速度

In[114]: timeit("findreplace('it is icy','i')", "from __main__ import findreplace")
Out[114]: 0.9927914671134204

不如替换或翻译快,但是可以。


0
# s1 == source string
# char == find this character
# repl == replace with this character
def findreplace(s1, char, repl):
    s1 = s1.replace(char, repl)
    return s1

# find each 'i' in the string and replace with a 'u'
print findreplace('it is icy', 'i', 'u')
# output
''' ut us ucy '''
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.