【问题标题】:Python 3: Convert string from utf-8 to ascii [duplicate]Python 3:将字符串从 utf-8 转换为 ascii [重复]
【发布时间】:2019-06-04 13:49:06
【问题描述】:

我正在使用 Python 3.x 并且有一个包含 utf-8 字符的字符串,如下所示:

link='https%3A%2F%2Fwww.google.com'

我现在想将字符串转换为 ascii,使其显示为“https://www.google.com”。我怎样才能做到这一点?我试过了

link.decode('utf-8')

抛出异常:

AttributeError: 'str' object has no attribute 'decode'

有没有一种简单的方法可以简单地将包含 utf-8 字符的字符串解码为纯 ascii 字符?

【问题讨论】:

  • URL 编码和 UTF-8 编码是两个独立的东西。
  • 该字符串中没有 UTF-8 字符(纯 ASCII 字符除外,当然技术上 也是 UTF-8 字符,很简单)。
  • 感谢您的澄清!

标签: python-3.x utf-8 ascii


【解决方案1】:

你应该使用urllib.parse.unquote,它会自动为你处理https://docs.python.org/3/library/urllib.parse.html#urllib.parse.unquote的解码:

$ python
Python 3.7.0 (v3.7.0:1bf9cc5093, Jun 26 2018, 23:26:24)
>>> from urllib.parse import unquote
>>> url = unquote('https%3A%2F%2Fwww.google.com')
>>> url
'https://www.google.com'

【讨论】:

  • 谢谢,正是我想要的。
猜你喜欢
  • 1970-01-01
  • 2015-08-06
  • 2021-12-31
  • 2011-06-19
  • 1970-01-01
  • 2013-08-09
  • 2017-06-10
  • 2010-10-24
  • 2011-05-17
相关资源
最近更新 更多