gpt4 book ai didi

python - python中的URL编码

转载 作者:IT老高 更新时间:2023-10-28 22:20:44 28 4
gpt4 key购买 nike

我在 urllib 或其他库中是否缺少用于此任务的简单方法? URL 编码将不安全的 ASCII 字符替换为“%”,后跟两个十六进制数字。

这是一个输入示例和我的预期输出:

Mozilla/5.0 (Linux; U; Android 4.0; xx-xx; Galaxy Nexus Build/IFL10C) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30

Mozilla%2F5.0+%28Linux%3B+U%3B+Android+4.0%3B+xx-xx%3B+Galaxy+Nexus+Build%2FIFL10C%29+AppleWebKit%2F534.30+%28KHTML%2C+like+Gecko%29+Version%2F4.0+Mobile+Safari%2F534.30

最佳答案

对于 Python 2.x,请使用 urllib.quote

Replace special characters in string using the %xx escape. Letters, digits, and the characters '_.-' are never quoted. By default, this function is intended for quoting the path section of the URL. The optional safe parameter specifies additional characters that should not be quoted — its default value is '/'.

示例:

In [1]: import urllib

In [2]: urllib.quote('%')
Out[2]: '%25'

编辑:

在您的情况下,为了用加号替换空格,您可以使用 urllib.quote_plus

示例:

In [4]: urllib.quote_plus('a b')
Out[4]: 'a+b'

对于 Python 3.x,请使用 quote

>>> import urllib
>>> a = "asdas#@das"
>>> urllib.parse.quote(a)
'asdas%23%40das'

对于带空格的字符串,使用 quote_plus

>>> import urllib
>>> a = "as da& s#@das"
>>> urllib.parse.quote_plus(a)
'as+da%26+s%23%40das'

关于python - python中的URL编码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8905864/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com