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.
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 filter
function
>>> "".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.replace
and str.translate
methods are 8 and 5 times faster than the accepted answer.
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. So, they all are excluded from the timing comparison.
Try 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.
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. 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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With