I want to do a string replace, to remove all of the special and unsafe characters used in a search phrase, to something suitable to be inserted into a Google URL.
I could use multiple instances of .replace or re.sub, but that seems inefficient. Is there a faster or more Pythonic way of doing this? I’m thinking I’m moving beyond beginner and into intermediate lately, because of all my attempts at making my code cleaner and more efficient.
Instead of doing the replacement yourself, I would suggest using
urllib.quote(), which returns a URL-safe string by converting special characters to%xxescapes.The benefit here is that you can easily obtain the original string from your URL safe version using
urllib.unquote()(and you don’t need to write the code yourself!).