python的string与Unicode转换,gbk字符串编码
2018-01-04 17:34
579 查看
问题一
字串前面少了u。
当遇见以下情况。
返回字符串为’\u82f9\u679c’的unicode时候。
str1 = '\u82f9\u679c' # 这里没有u,当传入参数不是unicode的时候 print str1 # 结果是 : \u82f9\u679c print u'\u82f9\u679c' # 结果是 : 苹果
解决方法:加上
u
str1 = '\u82f9\u679c' uni_result = str1.decode("unicode-escape") print uni_result # 结果是 : 苹果
问题二
字串前面多了u。
aa.text的结果如下
In[190]: aa.text Out[190]: u'\xe4\xb8\x8a\xe6\xb5\xb7A\xe8\x82\xa1' In[191]: print aa.text Out[191]: 上海Aè‚¡ In[192]: print '\xe4\xb8\x8a\xe6\xb5\xb7A\xe8\x82\xa1' Out[192]: 上海A股
使用utf-8编码时候,出问题。打印结果不对
In[191]: aa.text.encode('utf-8') Out[191]: '\xc3\xa4\xc2\xb8\xc2\x8a\xc3\xa6\xc2\xb5\xc2\xb7A\xc3\xa8\xc2\x82\xc2\xa1' In[192]: print aa.text.encode('utf-8') 上海A股
解决方案:去掉
u
In[193]: aa.text.encode('raw_unicode_escape') Out[193]: '\xe4\xb8\x8a\xe6\xb5\xb7A\xe8\x82\xa1' In[194]: print aa.text.encode('raw_unicode_escape') 上海A股
或者使用
bb = eval(repr(aa.text).lstrip('u')) print bb 上海A股
问题三
gbk的decode问题gbk的编码有时候在是
%C2%FA99%BC%F55这种格式,需要将之转化为python里面的
\xc2\xfa99\xbc\xf55这种格式。
gbk的编码如下,(中文:满99减5):
tmp_a = r'%C2%FA99%BC%F55' tmp_a = '%C2%FA99%BC%F55'
而在python中,编码应该如下:
\xc2\xfa99\xbc\xf55
可以看出差异为,需要将
%替换为
\x。使用如下函数:
def transGbk2Unicode(str_v):
str_s = str_v.replace(r'%', r'\x')
res = eval(repr(str_s).replace('\\\\', '\\'))
return res.decode('gb2312')
tmp_a = r'%C2%FA99%BC%F55' tmp_a = '%C2%FA99%BC%F55'
m = transGbk2Unicode(tmp_a)
print m
相关文章推荐
- JSON: Python Objects与String之间转换【json.dumps把python任意数据类型转换成字符串,json.loads把字符串转换为unicode编码】
- python 之编码转换 unicode, utf-8, utf-16, GBK
- python 中 string 和 unicode 字符串编码问题
- Python中unicode编码的字符串和其他格式的字符串之间进行转换
- 使用python将用ASCII表示的16进制unicode编码的ASCII字符串转换为unicode字符串
- Python 普通str字符串 和 unicode 字符串 及字符串编码探测、转换
- Python 中的编码转换 编码方案 中文解码 gbk , utf ,unicode
- python 2.x将raw_input()方式输入的字符串转换为unicode编码
- Python编码UNICODE GBK UTF-8字符集转换的正确姿势
- python:正确的对未知编码的字符串进行预处理-Unicode-UTF8-gbk
- Python的编码机制,unicode, utf-8, utf-16, GBK, GB2312,ISO-8859-1 等编码之间的转换。
- python 中文编码(unicode,gbk,utf8,ordinary string)
- 字符串编码格式相互转换Unicode --UTF-8 -- GBK
- python str方法转换为字符串 对于Unicode会调用系统默认编码
- 把unicode编码的十六进制字符串转换为汉字(Python2.7)
- C/C++ 各种字符编码字符串的转换 可用于XML文件的字符转化读写 (收集 GBK - UTF8 - Unicode - ANSI )
- Python如何将Unicode中文字符串转换成 string字符串
- python字符串和变量相加时出现,coercing to unicode need string or buffer nonetype found python 错误的解决
- Python中GBK, UTF-8和Unicode的编码问题
- Python 字符串操作(string替换、删除、截取、复制、连接、比较、查找、包含、大小写转换、