I have an HTTP request that I'm trying to conduct based on user input. To do that, I'll need to transform all non-alphanumeric characters to their corresponding percent For example, I want Broome Street
to transform to Broome%20Street
. Now, if spaces were all I was contending with, I would simply write a .replace(' ','%20')
, but I'm quite frankly not sure what else might be in there that I haven't considered. (Maybe I'm being stupid. Either way it's an scalable question.)
Is there a simple way, perhaps a library, that will quickly and simply transform a string into a URL? The only alternative is creating two lists and zipping them through a for-loop, and that's crazy.
There are a number of ways to do this - a few are described here: How to urlencode a querystring in Python?
Basically you're trying to perform "URL encoding". String replace and/or regex are not the best options for this, as you guessed, since there are several builtin options to take care of things for you (such as some non-obvious conversions that need to be handled)
...and don't use the first option shown on that linked page - you probably want to use
urllib.parse.quote_plus(...)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.