Alex Rivera | Logout

Remove specific characters from a string in Python

Asked 2010-10-15T03:46:21.147
730

I'm trying to remove specific characters from a string using Python. This is the code I'm using right now. Unfortunately, it appears to do nothing to the string.

for char in line:
    if char in " ?.!/;:":
        line.replace(char,'')

How do I do this properly?


See Why doesn't calling a string method (such as .replace or .strip) modify (mutate) the string? for the specific debugging question about what is wrong with this approach. Answers here mainly focus on how to solve the problem.

Edit
Report

1 Answer

72
>>> line = "abc#@!?efg12;:?"
>>> ''.join( c for c in line if  c not in '?:!/;' )
'abc#@efg12'
answered 2010-10-15T04:18:18.183

Your Answer