谈一谈python的字符串和输出

简介: 谈一谈python的字符串和输出

python3的字符串默认是unicode格式存储的,不必在前面加u说明。u'真的'和'真的'是一样的。


为什么有时候获取网页信息之后,我们输出结果到屏幕,查看一些中间变量的时候,会出现告知我们这样的错误:

UnicodeDecodeError: 'utf-8' codec can't decode bytes in position 0-1: unexpected
 end of data

Unicode解码错误: utf-8 编码规则不能解码位置0到1处的字节:数据结尾不正确(不是期待的)。


这就是因为编码转换失败了。网页自己是gbk编码,但是print输出的时候采用了utf-8编码,所以会出现无法识别的情况。


unicode字符串转为utf-8可以正确地转,但是gbk转为utf-8就不尽然了。这时,需要先将gbk编码转换为bytes,先encode,再decode。为什么要先encode也很容易记忆,就是……str类型只有encode方法可以调用。


print会使用系统默认编码方式,解码字节串然后输出。使用:

import sys
sys.getdefaultencoding()

可以获得当前系统的print编码。则,set就可以将print的编码方式设置为除了utf-8的其他方式。


比如:

sys.setdefaultencoding("utf-8")

就可以将编码设为utf-8,还有一个地方需要注意,python2.X和3.3、以及3.3后面的版本这里的处理有点不一样,在文章最后写。


sys.setdefaultencoding("GBK")

import sys #引用sys模块进来,并不是进行sys的第一次加载

sys.reload(sys) #重新加载sys,使getdefaultencoding()可以调用

sys.getdefaultencoding()

下面是将str变为bytes、utf-8和gbk编码的例子。



>>> su = u'哈哈'
>>> su
'哈哈'
>>> sut= su.encode("utf-8")
#转换成utf-8编码
>>> sut
b'\xe5\x93\x88\xe5\x93\x88'
>>> print(sut)
b'\xe5\x93\x88\xe5\x93\x88'
>>> print(su.decode('gbk'))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'str' object has no attribute 'decode'
#str类型只有encode方法可以调用
>>> tk= b'\xe5\x93\x88'
>>> tk
b'\xe5\x93\x88'
>>> print(tk.decode('utf-8'))
>>> import sys
>>> sys.getdefaultencoding()
'utf-8'
>>> sut += b'\0x5'
>>> sut
b'\xe5\x93\x88\xe5\x93\x88\x00x5'
>>> print(sut)
b'\xe5\x93\x88\xe5\x93\x88\x00x5'
>>>
>>> print(sut.decode('utf-8'))
哈哈 x5


如果使用python 2.x,直接reload()就可以了。

如果使用python3.0到3.3,需要

import imp
imp.reload(sys)
sys.setdefaultencoding("GBK")

如果使用python3.3以上版本,需要

import importlib
importlib.reload(sys)


#然后使用dir(sys)可以发现,sys已经没有了setdefaultencoding()方法,那怎么办?如果面对一个GBK文件,只好将文件以byte方式读取进来,再decode("GBK"),再输出。


with open("newgbk.txt", "rb") as file1:
  for i in file1.readlines():
    #print(i)
    print(i.decode('ISO-8859-6'))


目录
相关文章
|
12天前
|
Python
Python中的f-string:更优雅的字符串格式化
Python中的f-string:更优雅的字符串格式化
194 100
|
12天前
|
开发者 Python
Python中的f-string:高效字符串格式化的利器
Python中的f-string:高效字符串格式化的利器
236 99
|
16天前
|
Python
Python中的f-string:更优雅的字符串格式化
Python中的f-string:更优雅的字符串格式化
|
16天前
|
开发者 Python
Python f-strings:更优雅的字符串格式化技巧
Python f-strings:更优雅的字符串格式化技巧
|
16天前
|
开发者 Python
Python f-string:高效字符串格式化的艺术
Python f-string:高效字符串格式化的艺术
|
27天前
|
Python
使用Python f-strings实现更优雅的字符串格式化
使用Python f-strings实现更优雅的字符串格式化
|
2月前
|
Python
Python中的f-string:更简洁的字符串格式化
Python中的f-string:更简洁的字符串格式化
215 92
|
2月前
|
索引 Python
python 字符串的所有基础知识
python 字符串的所有基础知识
190 0
|
2月前
|
Python
Python字符串center()方法详解 - 实现字符串居中对齐的完整指南
Python的`center()`方法用于将字符串居中,并通过指定宽度和填充字符美化输出格式,常用于文本对齐、标题及表格设计。

推荐镜像

更多