如何在Python中对字符串进行URL参数编码

4

如何对字符串进行编码,以便在URL参数中传递编码后的字符串?

3个回答

8
使用urllib.quote_plus函数。以下是一个示例:
#!/usr/bin/python

print "Content-Type: text/html;charset=utf-8";
print

import urllib

str = "Hello World?"
str = urllib.quote_plus(str)

print str

输出: 你好+世界%3F


6
Python 3: str = urllib.parse.quote_plus(str) 可以翻译为:将变量 str 进行 URL 编码,代码如下:str = urllib.parse.quote_plus(str) - runcoderun

0

使用的库是urllib,请参见http://docs.python.org/2/library/urllib.html

>>> import urllib
>>> f = { 'eventName' : 'myEvent', 'eventDescription' : "cool event"}
>>> urllib.urlencode(f)
'eventName=myEvent&eventDescription=cool+event'

>>> urllib.quote_plus('string_of_characters_like_these:$#@=?%^Q^$')
'string_of_characters_like_these%3A%24%23%40%3D%3F%25%5EQ%5E%24'

0

使用 urllib.encode()

>>> import urllib
>>> f = { 'eventName' : 'myEvent', 'eventDescription' : "cool event"}
>>> urllib.urlencode(f)
'eventName=myEvent&eventDescription=cool+event'

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接