如何删除python中字符串中字符的所有实例?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22187233/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to delete all instances of a character in a string in python?
提问by
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?
为什么是这样?
回答by Blue Ice
Try str.replace():
尝试str.replace():
str="it is icy"
print str.replace("i", "")
回答by jpmc26
>>> 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 1argument.
由于您的代码只会替换第一个实例,因此我认为这就是您想要的。如果您想全部替换它们,请不要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.)
由于您无法替换字符串本身中的字符,因此您必须将其重新分配回变量。(本质上,您必须更新引用而不是修改字符串。)
回答by MaNKuR
replace()method will work for this. Here is the code that will help to remove character from string. lets say
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"
回答by thefourtheye
Strings are immutable in Python, which means once a string is created, you cannot alter the contents of the strings. If at all, you need to change it, a new instance of the string will be created with the alterations.
字符串在 Python 中是不可变的,这意味着一旦创建了字符串,就不能更改字符串的内容。如果您需要更改它,则会使用更改创建字符串的新实例。
Having that in mind, we have so many ways to solve this
考虑到这一点,我们有很多方法可以解决这个问题
Using
str.replace,>>> "it is icy".replace("i", "") 't s cy'Using
str.translate,>>> "it is icy".translate(None, "i") 't s cy'Using Regular Expression,
>>> import re >>> re.sub(r'i', "", "it is icy") 't s cy'Using comprehension as a filter,
>>> "".join([char for char in "it is icy" if char != "i"]) 't s cy'Using
filterfunction>>> "".join(filter(lambda char: char != "i", "it is icy")) 't s cy'
使用
str.replace,>>> "it is icy".replace("i", "") 't s cy'>>> "it is icy".translate(None, "i") 't s cy'使用正则表达式,
>>> import re >>> re.sub(r'i', "", "it is icy") 't s cy'使用理解作为过滤器,
>>> "".join([char for char in "it is icy" if char != "i"]) 't s cy'使用
filter功能>>> "".join(filter(lambda char: char != "i", "it is icy")) 't s 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.replaceand str.translatemethods are 8 and 5 times faster than the accepted answer.
str.replace和str.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 reis a bit overkill for a single character replacement. So, they all are excluded from the timing comparison.
注意:在这种情况下,理解方法和过滤器方法预计会更慢,因为它们必须创建列表,然后必须再次遍历它们以构造字符串。而re对于单个字符替换有点大材小用。因此,它们都被排除在时序比较之外。
回答by whackamadoodle3000
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. You can see the ipython console test below
按字符拆分将删除所有字符并将其转换为列表。然后我们使用 join 函数加入列表。您可以在下面看到 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.
不像替换或翻译那么快,但还可以。
回答by Michael Swartz
# 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 '''

