Skip to content
Advertisement

Replace special characters in a string in Python

I am using urllib to get a string of html from a website and need to put each word in the html document into a list.

Here is the code I have so far. I keep getting an error. I have also copied the error below.

JavaScript

Here is the error.

JavaScript

Advertisement

Answer

str.replace is the wrong function for what you want to do (apart from it being used incorrectly). You want to replace any character of a set with a space, not the whole set with a single space (the latter is what replace does). You can use translate like this:

JavaScript

This creates a mapping which maps every character in your list of special characters to a space, then calls translate() on the string, replacing every single character in the set of special characters with a space.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement