我需要测试一个字符串是否为Unicode,如果是UTF-8。在此之后,获取字符串的字节长度,包括BOM,如果它使用它的话。在Python中如何做到这一点呢?
同样出于教学目的,UTF-8字符串的字节列表表示是什么样子的?我很好奇UTF-8字符串在Python中是如何表示的。
后面的编辑: pprint做得很好。
发布于 2012-08-21 18:44:58
try:
string.decode('utf-8')
print "string is UTF-8, length %d bytes" % len(string)
except UnicodeError:
print "string is not UTF-8"在Python2中,str是一个字节序列,unicode是一个字符序列。您可以使用str.decode将字节序列解码为unicode,使用unicode.encode将字符序列编码为str。例如,u"é"是包含单个字符U+00E9的unicode字符串,也可以写为u"\xe9";编码为UTF-8将得到字节序列"\xc3\xa9"。
在Python3中,这种情况有所改变;bytes是一个字节序列,而str是一个字符序列。
发布于 2012-08-21 19:10:37
检查Unicode是否为
>>>a = u'F'
>>>isinstance(a, unicode)
True检查它是UTF-8还是ASCII
>>>import chardet
>>>encoding = chardet.detect('AA')
>>>encoding['encoding']
'ascii'发布于 2012-08-21 18:44:32
我绝对推荐Joel Spolsky的The Absolute Minimum Every Software Developer Absolutely, Positively Must Know about Unicode and Character Sets (No Excuses!),如果你还没有读过的话。
对于Python的Unicode和编码/解码机制,启动here。要获取以utf-8编码的Unicode字符串的字节长度,您可以这样做:
print len(my_unicode_string.encode('utf-8'))您的问题被标记为python-2.5,但请注意,这在Python 3+中有一些变化。
https://stackoverflow.com/questions/12053107
复制相似问题