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中对应两列完全相同的脚本:
就直接按照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
相关文章推荐
- Android之获取手机上的图片和视频缩略图thumbnails
- android string.xml文件中的整型和string型代替
- Android java 与 javascript互访(相互调用)的方法例子
- Python动态类型的学习---引用的理解
- Python3写爬虫(四)多线程实现数据爬取
- 垃圾邮件过滤器 python简单实现
- 下载并遍历 names.txt 文件,输出长度最长的回文人名。
- install and upgrade scrapy
- Scrapy的架构介绍
- Centos6 编译安装Python
- 使用Python生成Excel格式的图片
- 让Python文件也可以当bat文件运行
- [Python]推算数独
- Python中zip()函数用法举例
- Python中map()函数浅析
- Python将excel导入到mysql中
- android上改变listView的选中颜色
- String.intern