今天遇到一个字符串问题,比较xml文件中读出的字符串,打印出来一样,用==比较(==在python中就是值比较)却是false,百思不得其解
debug时,思考可能产生原因
1.首尾字符
譬如有的字符串末尾有空格、换行符,就会导致不相等
解决办法:
str1 = str1.strip()
2.编码问题
我担心是因为编码方式不一样所以比较出来不一样,
特意去查了一下 XML中间的CDATA就是表示纯文本格式
但是譬如用string = answer.childNodes[0].data
通过type(string)可知,string会是Unicode格式
python2.x中
Unicode转utf-8: string2 = string1.encode("utf-8"),string1为Unicode,string2为utf-8
utf-8转Unicode: string2 = string1.decode("utf-8"),string2为Unicode,string1为utf-8
3.常遇到编码问题
‘utf8’ codec can’t decode byte 0xa1
原因:出现了一些utf-8无法编码的字符
解决方法:with codecs.open(path, "r", "ISO-8859-1") as input:
iso8859-1属于单字节编码,最多能表示的字符范围是0-255,应用于英文系列
4.其他编码问题
https://www.cnblogs.com/daxiong2014/p/5522672.html