我必须在Python中做什么来找出字符串的编码?


当前回答

在Python-3中,我必须理解字符串是否像b='\x7f\x00\x00\x01'或b='127.0.0.1'我的解决方案是这样的:

def get_str(value):
    str_value = str(value)
    
    if str_value.isprintable():
        return str_value

    return '.'.join(['%d' % x for x in value])

对我有用,我希望对有需要的人有用

其他回答

Unicode不是一种编码——引用Kumar McMillan的话:

如果ASCII, UTF-8和其他字节字符串是“text”… ...那么Unicode就是“文本性”; 它是文本的抽象形式

读一读McMillan在PyCon 2008上的Unicode In Python,完全解密的演讲,它比Stack Overflow上的大多数相关答案更好地解释了事情。

注意,在Python 3中,这样说并不公平:

字符串是UTFx的任何x(例如。use UTF8) str是Unicode 字符串是Unicode字符的有序集合

Python的str类型(通常)是Unicode码位序列,其中一些映射到字符。


即使在Python 3上,回答这个问题也不像您想象的那么简单。

测试ascii兼容字符串的一个明显的方法是尝试编码:

"Hello there!".encode("ascii")
#>>> b'Hello there!'

"Hello there... ☃!".encode("ascii")
#>>> Traceback (most recent call last):
#>>>   File "", line 4, in <module>
#>>> UnicodeEncodeError: 'ascii' codec can't encode character '\u2603' in position 15: ordinal not in range(128)

这个错误区分了不同的情况。

在Python 3中,甚至有一些字符串包含无效的Unicode代码点:

"Hello there!".encode("utf8")
#>>> b'Hello there!'

"\udcc3".encode("utf8")
#>>> Traceback (most recent call last):
#>>>   File "", line 19, in <module>
#>>> UnicodeEncodeError: 'utf-8' codec can't encode character '\udcc3' in position 0: surrogates not allowed

用同样的方法来区分它们。

一种简单的方法是检查unicode是否是内置函数。如果是,你在python2中,你的字符串将是一个字符串。要确保所有内容都使用unicode,可以执行以下操作:

import builtins

i = 'cats'
if 'unicode' in dir(builtins):     # True in python 2, False in 3
  i = unicode(i)

在Python-3中,我必须理解字符串是否像b='\x7f\x00\x00\x01'或b='127.0.0.1'我的解决方案是这样的:

def get_str(value):
    str_value = str(value)
    
    if str_value.isprintable():
        return str_value

    return '.'.join(['%d' % x for x in value])

对我有用,我希望对有需要的人有用

在python3中,所有字符串都是Unicode字符的序列。有一种bytes类型保存原始字节。

在python2中,字符串的类型可以是str或unicode。你可以用如下代码来区分:

def whatisthis(s):
    if isinstance(s, str):
        print "ordinary string"
    elif isinstance(s, unicode):
        print "unicode string"
    else:
        print "not a string"

这并不区分“Unicode或ASCII”;它只区分Python类型。Unicode字符串可以由ASCII范围内的纯字符组成,字节字符串可以包含ASCII、编码的Unicode,甚至是非文本数据。