您的位置:首页 > 编程语言 > Python开发

Python 中string和unicode的区别

2015-12-23 11:18 706 查看
前段时间在写一个excel文件内容比较的脚本时遇到关于string对象和unicode对象的比较问题。开始写的时候没有先获取对象的type查看,

就直接按照string的比较方法进行操作,结果总是得不到我想要的结果,后来打印type出来才发现里面的类型不仅有string还有unicode等其他的类型。

于是就把string对象和unicode对象的区别仔细回顾了一下,现记录下来避免遗忘。

两者的区别

string直接用引号来表示,unicode在引号前加一个u

len(string)返回string的字节数,len(unicode)返回的是字符数

直接输入的string常量会用系统缺省编码方式来编码

print (unicode)不会乱码

string 和unicode 是可以相互转化的。

decode是string2unicode,encode是unicode2string

知道了上面的区别之后,就可以再次修改脚本进行excel中的内容比较了,首先判断type是否是unicode,如果是则先进行encode,然后再和string

类型的比较。

附比较excel中对应两列完全相同的脚本:

'''
get the same ref and same eng string and write to a new excel file
'''
def get_ref_same_eng_same(self,ori_string_map,dest_string_map,ori_file,sameeng_filename):
self.log.info(Log.INFO,"=====Start to get_ref_same_eng_same =======")
same_ref_same_eng_ref =[]
same_ref_same_eng_ori_eng =[]
same_ref_same_eng_dest_eng = []
for key in dest_string_map.keys():
if key in ori_string_map.keys():
mtype = str(type(dest_string_map.get(key)))
if("string" in mtype):
if (dest_string_map.get(key).upper().strip() == ori_string_map.get(key).upper().strip()):
same_ref_same_eng_ref.append(key)
same_ref_same_eng_ori_eng.append(ori_string_map.get(key))
same_ref_same_eng_dest_eng.append(dest_string_map.get(key))
else:
continue
elif("unicode" in mtype):
#print "type unicode:",type(dest_string_map.get(key))
if (dest_string_map.get(key).encode("utf-8").upper().strip() == ori_string_map.get(key).encode("utf-8").upper().strip()):
same_ref_same_eng_ref.append(key)
same_ref_same_eng_ori_eng.append(ori_string_map.get(key))
same_ref_same_eng_dest_eng.append(dest_string_map.get(key))
else:
continue
else:
if (dest_string_map.get(key) == ori_string_map.get(key)):
same_ref_same_eng_ref.append(key)
same_ref_same_eng_ori_eng.append(ori_string_map.get(key))
same_ref_same_eng_dest_eng.append(dest_string_map.get(key))
else:
continue
else :
continue
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Python string