创建没有编码的查询字符串
Create query string without encoding
我想创建一个查询字符串,但不对 @
、!
或 ?
等特殊字符进行编码。
这是我的代码:
payload = {"key": "value", "key2": "value2",
"email": "test@hello3.ch", "password": "myPassword54321!?"}
print(urllib.parse.urlencode(payload))
现在我得到这样的输出:
password=myPassword54321%21%3F&email=test%40hello3.ch
如何使我的输出看起来像这样:
password=myPassword54321!?&email=test@hello3.ch
代表的字符替换 %xx
字符转义
from urllib.parse import urlencode, unquote
print(unquote(urlencode(payload)))
# key=value&key2=value2&email=test@hello3.ch&password=myPassword54321!?
如果您不想使用 urlencode
的编码功能,您最好不要使用它,因为它不会做太多其他事情。如果你只想打印由 &
符号分隔的键值对,每个键值对由 =
连接,使用 str.join
和 str.format
很简单:
print("&".join("{}={}".format(key, value) for key, value in payload.items()))
我想创建一个查询字符串,但不对 @
、!
或 ?
等特殊字符进行编码。
这是我的代码:
payload = {"key": "value", "key2": "value2",
"email": "test@hello3.ch", "password": "myPassword54321!?"}
print(urllib.parse.urlencode(payload))
现在我得到这样的输出:
password=myPassword54321%21%3F&email=test%40hello3.ch
如何使我的输出看起来像这样:
password=myPassword54321!?&email=test@hello3.ch
%xx
字符转义
from urllib.parse import urlencode, unquote
print(unquote(urlencode(payload)))
# key=value&key2=value2&email=test@hello3.ch&password=myPassword54321!?
如果您不想使用 urlencode
的编码功能,您最好不要使用它,因为它不会做太多其他事情。如果你只想打印由 &
符号分隔的键值对,每个键值对由 =
连接,使用 str.join
和 str.format
很简单:
print("&".join("{}={}".format(key, value) for key, value in payload.items()))