为URL Python编码字符串

2024-09-28 20:46:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下需要为URL编码的URL:This is currently the top headline on Reddit TIL Pimps wear lots of gold jewelry bought at pawn shops to “re-pawn” for bail money since cash is confiscated upon arrest but jewelry is not

我遇到了一个问题,因为这个字符串包含unicode字符,特别是引号。在

我尝试过urllib.quote_plus(message),但这引发了以下异常:

Traceback (most recent call last):
  File "testProgram.py", line 44, in <module>
    main()                                      # Run
  File "testProgram.py", line 41, in main
    testProgram(headline)                                   # Make phone call
  File "testProgram.py", line 31, in testProgram
    urllib.quote_plus(message)
  File "/usr/local/Cellar/python/2.7.8_1/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib.py", line 1293, in quote_plus
    s = quote(s, safe + ' ')
  File "/usr/local/Cellar/python/2.7.8_1/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib.py", line 1288, in quote
    return ''.join(map(quoter, s))
KeyError: u'\u201c'

有人知道为什么吗?在


Tags: inpyurlmessageislineplusurllib
1条回答
网友
1楼 · 发布于 2024-09-28 20:46:39

如果message是Unicode字符串,请尝试:

urllib.quote_plus(message.encode('utf-8'))

遗憾的是,utf-8并不是在url中普遍使用的(我不认为有一个被普遍接受的标准,唉),但由于其“通用”的特性,它非常流行(每个Unicode字符都可以用utf-8表示,而其他许多流行编码则不是这样)。在

相关问题 更多 >