Since Python strings are immutable, we'll use a list of chars instead to exercise in-place string manipulation as you would get with a C string.
create a list as a string builder
In [45]:
def remove_char(string, char):
newString = []
for i in string:
if char != i:
newString.append(i)
return "".join(newString)
In [46]:
def remove_char2(string, char):
return string.translate(None, char)
def remove_char3(string, char):
return string.replace(char, "")
In [47]:
from nose.tools import assert_equal
def testWith(func):
assert_equal(func("tamamdir arAda", "a"), "tmmdir rAd")
assert_equal(func("wlkwlkfew wifiw longgglonggggw", "w"), "lklkfe ifi longgglongggg")
assert_equal(func("yu*lkke*", "*"), "yulkke")
print('Success')
testWith(remove_char)
testWith(remove_char2)
testWith(remove_char3)
In [49]:
import timeit
print "remove_char", timeit.timeit(
"remove_char('wlkwlkfew wifiw longgglonggggw', 'a')",
"from __main__ import remove_char", number=1200000)
print "remove_char2", timeit.timeit(
"remove_char2('wlkwlkfew wifiw longgglonggggw', 'a')",
"from __main__ import remove_char2", number=1200000)
print "remove_char3", timeit.timeit(
"remove_char3('wlkwlkfew wifiw longgglonggggw', 'a')",
"from __main__ import remove_char3", number=1200000)
In [ ]: