gpt4 book ai didi

python - 使用 Python 将 UTF-8 解码为 URL

转载 作者:太空宇宙 更新时间:2023-11-04 00:48:33 25 4
gpt4 key购买 nike

我有以下以 utf-8 编码的 url。

url_input = u'https://www.gumtree.com//p/uk-holiday-rentals/1bedroon-flat-\xa3250pw-all-bills-included-/1174092955'

我需要废弃此网页,为此我需要具有以下 url_output(未读取 unicode)。

url_output=https://www.gumtree.com//p/uk-holiday-rentals/1bedroon-flat-£250pw-all-bills-included-/1174092955

当我打印 url_input 时,我得到 url_output:

print(url_input)
https://www.gumtree.com//p/uk-holiday-rentals/1bedroon-flat-£250pw-all-bills-included-/1174092955

但是我没有找到将 url_input 转换为 url_output 的方法。根据论坛,打印函数在 Python 2.7 上使用 ascii 解码,但 ascii 不应读取 \xa3 并且 url_input.encode('ASCII') 不起作用。

有人知道我该如何解决这个问题吗?提前致谢 !

最佳答案

当您打印 url_input 时,您得到所需的 url_output 只是因为您的终端理解 UTF-8 并且可以正确表示 \xa3

您可以使用 str.encode 将字符串编码为 ASCII,但您必须替换(使用 ?)或忽略不是 ascii 的字符:

url_output = url_input.encode("ascii", "replace")
print(url_output)

将打印:

https://www.gumtree.com//p/uk-holiday-rentals/1bedroon-flat-?250pw-all-bills-included-/1174092955

url_output = url_input.encode("ascii", "ignore")
print(url_output)

将打印:

https://www.gumtree.com//p/uk-holiday-rentals/1bedroon-flat-250pw-all-bills-included-/1174092955

您无法获得带有 £ ascii 字符的输出字符串,因为该字符的值大于 127。

关于python - 使用 Python 将 UTF-8 解码为 URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38186925/

25 4 0
文章推荐: javascript - 使用 gulp.watch 会抛出 "TypeError: Object # has no method ' watch'"