简体   繁体   English

在 Python 中对字符串进行百分比编码

[英]Percent-encoding a string in Python

I have an HTTP request that I'm trying to conduct based on user input.我有一个 HTTP 请求,我正在尝试根据用户输入进行处理。 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 .为此,我需要将所有非字母数字字符转换为相应的百分比。例如,我希望将Broome Street转换为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.现在,如果空间是我所争论的全部,我会简单地写一个.replace(' ','%20') ,但坦率地说,我不确定还有什么我没有考虑过。 (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?有没有一种简单的方法,也许是一个库,可以快速简单地将字符串转换为 URL? The only alternative is creating two lists and zipping them through a for-loop, and that's crazy.唯一的选择是创建两个列表并通过 for 循环压缩它们,这太疯狂了。

There are a number of ways to do this - a few are described here: How to urlencode a querystring in Python?有很多方法可以做到这一点 - 这里描述了一些: 如何在 Python 中对查询字符串进行 urlencode?

Basically you're trying to perform "URL encoding".基本上,您正在尝试执行“URL 编码”。 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(...)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM