如果你想要一个明确代表你所拥有的ASCII字符串,而不丢失任何信息,答案很简单:
不要使用编码/解码,使用repr()
函数(Python 2.X)或ascii()
函数(Python 3.x).
你说"它的编码各不相同".我想通过"它"你的意思是Python 2.x"字符串",它实际上是一个字节序列.
回答第一部分:如果你不知道那个编码字符串的编码,那么不,根本就没有办法做任何有意义的事情*.如果您确实知道编码,那么第一步是将您str
转换为unicode
:
encoded_string = i_have_no_control()
the_encoding = 'utf-8' # for the sake of example
text = unicode(encoded_string, the_encoding)
Run Code Online (Sandbox Code Playgroud)
然后,如果您愿意,可以将您的unicode对象重新编码为ASCII.
ascii_garbage = text.encode('ascii', 'replace')
Run Code Online (Sandbox Code Playgroud)
*有猜测编码的启发式方法,但它们很慢且不可靠.这是Python中的一次出色尝试.
归档时间: |
|
查看次数: |
9230 次 |
最近记录: |