python一个汉字的长度是多少?

Python049

python一个汉字的长度是多少?,第1张

这要看使用的哪种编码方式,utf-8的话用了3个字节,GBK的话是用了两个

>>> '汉'.encode('utf-8')

b'\xe6\xb1\x89'

>>> '汉'.encode('GBK')

b'\xba\xba'

python2默认使用ascii编码,通过在文件头部添加【#

-*-

coding:

utf-8

-*-】可以设置成utf8,python3默认是使用unicode。

如果解决了您的问题请采纳!

如果未解决请继续追问!

#coding=utf-8

test_str = u'提问123'

print len(test_str) # 输出5

或者

#coding=utf-8

test_str = '提问123'

test_str_unicode = test_str.decode('utf-8')

print len(test_str_unicode) # 输出5

求这种长度可以转化成求解码(unicode)的长度;报UnicodeDecodeError,应该是直接用了test_str.encode('utf-8'),这是编码。