1. 程式人生 > >[轉載] python 計算字符串長度

[轉載] python 計算字符串長度

itl val tle 自然 log length gpo 數量 文字

本文轉載自: http://www.sharejs.com/codes/python/4843

python 計算字符串長度,一個中文算兩個字符,先轉換成utf8,然後通過計算utf8的長度和len函數取得的長度,進行對比即可知道字符串內中文字符的數量,自然就可以計算出字符串的長度了。

value=u‘腳本12‘
length = len(value)
utf8_length = len(value.encode(‘utf-8‘))
length = (utf8_length - length)/2 + length
print(length)

結果輸出6

[轉載] python 計算字符串長度