0 votes
1 view
in Python by (47.8k 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 " ?.!/;:": 

line.replace(char,'')

How do I do this properly?

1 Answer

0 votes
by (107k 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.

Or

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

import re 

line = re.sub('[[email protected]#$]', '', 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.8k points)
0 votes
1 answer
asked Oct 4, 2019 in Python by Sammy (47.8k points)
Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...