我正在做一个Python项目,我必须将字符串编码为ASCII才能使用它,然后将其取回并将其转换回Unicode。问题是该字符串可能包含重音符号之类的字符,这些字符不在 ASCII 字符集中。我想在我的字符串中以某种形式转义它们,然后将它们毫无损失地收回。
我尝试使用 .encode 和 .decode 进行探索,但没有成功,并查看了该网站上的一些答案,但没有一个能够同时转换编码和解码。我见过Python中的ascii函数,但它没有相反的。
我会使用
urllib.parse.quote
和urllib.parse.unquote
来达到这个目的,简单的例子:
import urllib.parse
text_with_accent = "El Niño"
ascii_text = urllib.parse.quote(text_with_accent)
print(ascii_text) # El%20Ni%C3%B1o
print(ascii_text.isascii()) # True
original_text = urllib.parse.unquote(ascii_text)
print(text_with_accent==original_text) # True
urllib.parse
是标准库的一部分,因此您不需要安装python
本身以外的任何内容。