Python 中string和unicode的区别

前段时间在写一个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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值