简体   繁体   English

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

[英]How to delete all instances of a character in a string in python?

How do I delete all the instances of a character in this string?如何删除此字符串中某个字符的所有实例? Here is my code:这是我的代码:

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

However, if I run this, this is what happens:但是,如果我运行它,则会发生以下情况:

>>> 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

Why is this?为什么是这样?

Strings are immutable in Python, which means once a string is created, you cannot alter the contents of the strings.字符串在 Python 中是不可变的,这意味着一旦创建了字符串,就不能更改字符串的内容。 If at all, you need to change it, a new instance of the string will be created with the alterations.如果您需要更改它,则会使用更改创建字符串的新实例。

Having that in mind, we have so many ways to solve this考虑到这一点,我们有很多方法可以解决这个问题

  1. Using str.replace ,使用str.replace

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

     >>> "it is icy".translate(None, "i") 'ts cy'
  3. Using Regular Expression,使用正则表达式,

     >>> import re >>> re.sub(r'i', "", "it is icy") 'ts cy'
  4. Using comprehension as a filter,使用理解作为过滤器,

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

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

Timing comparison时序比较

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")

Result结果

1.64474582672
0.29278588295
0.311302900314

str.replace and str.translate methods are 8 and 5 times faster than the accepted answer. str.replacestr.translate方法比接受的答案快8倍和5倍。

Note: Comprehension method and filter methods are expected to be slower, for this case , since they have to create list and then they have to be traversed again to construct a string.注意:在这种情况下,理解方法和过滤器方法预计会更慢,因为它们必须创建列表,然后必须再次遍历它们以构造字符串。 And re is a bit overkill for a single character replacement.re对于单个字符替换来说有点矫枉过正。 So, they all are excluded from the timing comparison.因此,它们都被排除在时序比较之外。

Try str.replace() :尝试str.replace()

my_string = "it is icy"
print my_string.replace("i", "")
>>> x = 'it is icy'.replace('i', '', 1)
>>> x
't is icy'

Since your code would only replace the first instance, I assumed that's what you wanted.由于您的代码只会替换第一个实例,因此我认为这就是您想要的。 If you want to replace them all, leave off the 1 argument.如果您想全部替换它们,请不要使用1参数。

Since you cannot replace the character in the string itself, you have to reassign it back to the variable.由于您无法替换字符串本身中的字符,因此您必须将其重新分配回变量。 (Essentially, you have to update the reference instead of modifying the string.) (本质上,您必须更新引用而不是修改字符串。)

replace() method will work for this. replace()方法将为此工作。 Here is the code that will help to remove character from string.这是有助于从字符串中删除字符的代码。 lets say让我们说

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"

I suggest split (not saying that the other answers are invalid, this is just another way to do it):我建议拆分(不是说其他​​答案无效,这只是另一种方法):

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

Splitting by a character removes all the characters and turns it into a list.按字符拆分将删除所有字符并将其转换为列表。 Then we join the list with the join function.然后我们使用 join 函数加入列表。 You can see the ipython console test below您可以在下面看到 ipython 控制台测试

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

And the speed...而且速度...

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

Not as fast as replace or translate, but ok.不像替换或翻译那么快,但还可以。

# 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 '''

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM