python2 与 python3 编码问题总结

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zjm750617105/article/details/82724315

之前遇到过好多各种各样的问题, 特别是在python2下, 先在准备总结, 遇到一个总结一个:

  1. unicode 字符在python2下采用 ,在python3下统一为 string 类型.
    那么如何在python2下将一句话中的所有unicode字符转化为str类型呢?
    下面几种都试试, 不行就直接换python3吧.
# 数字
true = u'1'
print(type(true))
if type(true) == unicode:
  true = true.encode('utf-8')
  true = eval(true)
print(true)
# 也可以
import numpy as np
np.array([a], dtype=np.int)
a = '你好你好'
type(a)
Out[95]: str
a.decode('utf-8')
Out[96]: u'\u4f60\u597d\u4f60\u597d'
type(a.decode('utf-8'))
Out[97]: unicode
然后也不好处理
print(type(line)) # unicode
line = line.decode("unicode_escape") #去除unicode
line = line.encode("UTF-8") #重新编码

猜你喜欢

转载自blog.csdn.net/zjm750617105/article/details/82724315
今日推荐