Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
in Python by (47.6k points)

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 " ?.!/;:": 


How do I do this properly?

1 Answer

0 votes
by (106k points)

Strings in Python are immutable and they can not 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 assign it to line in order to have that variable take the new value, with those characters removed.


You can use a regular expression replacement with re.sub method:-

import re 

line = re.sub('[!@#$]', '', line)

To know more about this you can have a look at the following video tutorial:-

Related questions

0 votes
1 answer
0 votes
1 answer
asked Sep 10, 2019 in Python by Sammy (47.6k points)
0 votes
1 answer

Browse Categories