首页 > Python中文字符串长度的问题?

Python中文字符串长度的问题?

用两种方式查看字符串长度。
第一种,读取文件test.txt,
test.txt中存放“你好”,
读取出来,然后查看长度。
代码如下:

#coding=utf-8

f = open( "test.txt","r" )
str = f.read()

print len( str.decode( 'utf-8' ) )
print type( str )

第二种,直接将字符串写在代码中
如下:

str = "你好"

print len( str.decode( 'utf-8' ) )

第二种能正确查看长度但是第一种却不能正确显示,为什么呢?


顺便再查查你文件里面的文件编码是什么


是一样的,第一种里面你str里面还有换行符,所以会长度会多一个,你把换行符去掉就是一样的。

python#coding=utf-8

f = open("test.txt","r")
str = f.read().strip()

print len(str) # 6
print len(str.decode('utf-8')) # 2

str = "你好"
print len(str) # 6
print len(str.decode('utf-8')) # 2
【热门文章】
【热门文章】