python判断是否含有中文字符及长度

2025-03-21 10:04:59
推荐回答(1个)
回答(1):

1
2
3
4

#coding=utf-8

test_str = u'提问123'
print len(test_str) # 输出5

或者

1
2
3
4
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'),这是编码。