Already tried using: name = str.replace(name, ",","") but either i don't know what should I import into module or should i use different command
or getting an error: TypeError: descriptor 'replace' requires a 'str' object but received a 'list'
Would anyone tell me how to do it ?
Quiet urgent ..... ;)
Hi Dr Obx,
You can use strip() or replace() method.
str = " Anil Kesariya "
new_str = str.strip()
# o/p: Anil Kesariya
This method will remove unwanted space from left and right side of string.
If you want to remove the space or any symbolic pattern from whole string than you can use replace().
eg:1 remove space
str = " A n i l K e s a r i y a "
new_str = str.strip(" ","")
o/p : Anilkesariya
eg:2 remove "
str = Anil"kesari"ya'
new_str = str.replace('"',"")
Hope this will help.
Hello my friend;
Strings in python are immutable (can't be changed). Because of this, the effect of line.replace(...) is just to create a new string, rather than changing the old one. You need to rebind (assign) it to line in order to have that variable take the new value, with those characters removed.
Also, the way you are doing it is going to be kind of slow, relatively. It's also likely to be a bit confusing to experienced pythonators, who will see a doubly-nested structure and think for a moment that something more complicated is going on.
You can instead use str.translate: (https://docs.python.org/2/library/stdtypes.html#str.translate)
line = line.translate(None, '!@#$')
which only works on Python 2.6 and newer Python 2.x versions * —
or regular expression replacement with re.sub (https://docs.python.org/2/library/re.html#re.sub)
line = re.sub('[!@#$]', '', line)
Here is an example:
s = "this is a string"
l = list(s) # convert to list
l = "" # "delete" letter h (the item actually still exists but is empty)
l[1:2] =  # really delete letter h (the item is actually removed from the list)
del(l) # another way to delete it
p = l.index("a") # find position of the letter "a"
del(l[p]) # delete it
s = "".join(l) # convert back to string
def findreplace(m_string, char):
m_string = list(m_string)
for k in m_string:
if k == char:
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")
str.replace and str.translate methods are 8 and 5 times faster.
Please try to give a substantial answer. If you wanted to comment on the question or answer, just use the commenting tool. Please remember that you can always revise your answers - no need to answer the same question twice. Also, please don't forget to vote - it really helps to select the best questions and answers!
About This Community
|Asked: 9/9/15, 6:04 PM|
|Seen: 1031 times|
|Last updated: 6/22/16, 4:15 AM|