【问题标题】:Encoding string to Windows-1252 URL format in Python 3 [duplicate]在 Python 3 中将字符串编码为 Windows-1252 URL 格式 [重复]
【发布时间】:2019-04-15 02:23:28
【问题描述】:

我想像这样表示字符串中的所有字符 table.

但是当我这样做时

raw = 'æøå'
encoded = raw.encode('cp1252')
print(encoded)

我明白了

>>> b'\xe6\xf8\xe5'

我想要的是

>>> %E6%F8%E5

作为在 URL 中使用的字符串。

【问题讨论】:

  • 没有这样的东西。 1252 是拉丁代码页。 URLs 虽然有自己的 编码,与代码页无关。您在问如何对该字符串进行 URL 编码。
  • @PanagiotisKanavos:Latin-1 是一个不同的标准。 CP-1252 与该标准不同,不要将两者等同起来。当然,这不是 CP1252 编码输出是完全正确的。
  • @MartijnPieters 是的,我知道,但我已经厌倦了第 N 次写一整篇文章来描述 cmets 中的编码。 OP 仍然在问错误的事情,混淆了 URL 编码的字符代码页
  • @PanagiotisKanavos:绝对。 urllib.parse.quote() 会为您处理编码。

标签: python python-3.x encode urlencode


【解决方案1】:

您必须使用 urllib 工具“引用”您的字符串。

import urllib.parse

raw = 'æøå'
print(urllib.parse.quote(raw, encoding='cp1252'))
# returns "%E6%F8%E5"

【讨论】:

  • 不需要单独编码。 urlib.parse.quote() 直接接受编码参数。
  • 使用urllib.parse.quote(raw, encoding='cp1252'),完全跳过raw.encode()调用。
  • @MartijnPieters 感谢您提供的信息,我刚刚发现了这一点。答案已更新
  • 有时您确实需要处理bytes,此时我建议您使用urllib.parse.quote_from_bytes(),以明确说明正在做什么。此外,OP 可能想要使用quote_plus(),而不是quote(),因为其中绝大多数都想要application/x-www-form-urlencoded content type variant
猜你喜欢
  • 2012-09-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-09-08
  • 2017-10-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多