1.环境
python版本:Python 2.7.5
2.问题描述
从文件中读取了文本直想和固定的字符串比较,文本值看上去一样,但是比较结果是False
3.问题代码
#coding=utf-8
filePath = './test.txt'
testStr = '红糖博客'
with open(filePath,'r') as msgfile:
for item in msgfile:
if item == testStr:
print('ok')
print(item)
上面代码的输出结果:
红糖博客
并没有输出ok,这个其实和python2.*的默认的编码格式有关系,下面这段话很重要
在Python2中,普通字符串是以8位ASCII码进行存储的,而Unicode字符串则存储为16位unicode字符串,这样能够表示更多的字符集。使用的语法是在字符串前面加上前缀 u。 在Python3中,所有的字符串都是Unicode字符串。
4.解决方案:
#coding=utf-8
filePath = './test.txt'
testStr = '红糖博客'
with open(filePath,'r') as msgfile:
for item in msgfile:
if item.strip().decode('utf-8') == testStr.decode('utf-8'):
print('ok')
print(item)
ok正常输出!!