python文本字符串与字节字符串

python中的字符串一直是困扰小编的一大难题,相信大家伙也曾体验过被各种编码支配的恐惧吧。不过没关系,相信你读了这篇文章,一定会对python字符串豁然开朗!
代码链接:https://github.com/princewen/professional-python3
一、字符串类型
python3:
python语言有两种不同的字符串,一个用于存储文本,一个用于存储原始字节。
文本字符串内部使用Unicode存储,字节字符串存储原始字节并显示ASCII。

python3中,文本型字符串类型被命名为str,字节字符串类型被命名为bytes。
正常情况下,实例化一个字符串会得到一个str实例,如果希望得到一个bytes实例,需要在文本之前添加b字符。


text_str = 'The quick brown fox jumped over the lazy dogs'
print (type(text_str)) #output : <class 'str'>
 
 
byte_str = b'The quick brown fox jumped over the lazy dogs'
print (type(byte_str)) #output : <class 'bytes'>

python2:

python2中也有两种字符串,不过,python3中的str类在python2中名称为unicode,但是,python3中的bytes类在python2中名称为str类。
这意味着在python3中str类是一个文本字符串,而在python2中str类是一个字节字符串。
若不使用前缀实例化字符串,则返回一个str类(这里是字节字符串!!!),如果想要得到一个文本字符串,需要在字符串前面加上u字符。

byte_str = 'The quick brown fox jumped over the lazy dogs'
#output : <type 'str'>
print type(byte_str)
 
text_str = u'The quick brown fox jumped over the lazy dogs'
#output : <type 'unicode'>
print type(text_str)

二、字符串转换
python3:

可以在str与bytes之间进行类型转换,str类包含一个encode方法,用于使用特定编码将其转换为一个bytes。于此类似,bytes类包含一个decode方法,接受一个编码作为单个必要参数,并返回一个str。另一个需要注意的是,python3中永远不会尝试隐式地在一个str与一个bytes之间进行转换,需要显式使用str.encode 或者 bytes.decode方法。


#output :  b'The quick brown fox jumped over the lazy dogs'
print (text_str.encode('utf-8'))
 
#output : The quick brown fox jumped over the lazy dogs
print (byte_str.decode('utf-8'))
 
#output : False
print ('foo' == b'foo')
 
#Output : KeyError: b'foo'
d={'foo':'bar'}
print (d[b'foo'])
 
#Output : TypeError: Can't convert 'bytes' object to str implicitly
print ('foo'+b'bar')
 
#Output : TypeError: %b requires bytes, or an object that implements __bytes__, not 'str'
print (b'foo %s' % 'bar')
 
#output : bar b'foo'
print ('bar %s' % b'foo')

python2:

与python3不同的是,python2会在文本字符串和字节字符串之间尝试进行隐式转换。
该工作机制是,如果解释器遇到一个不同种类的字符串混合操作,解释器首先会将字节字符串转换为文本字符串,然后对文本字符串进行操作。
解释器在将字节字符串转换为文本字符串的过程中使用隐式解码,python2中默认编码几乎总是ASCII.
我们可以使用sys.getdefaultencoding 方法来查看默认编码方式。

#output :  foobar
print 'foo'+u'bar'
 
#output : ascii
print sys.getdefaultencoding()
 
#output : False
print 'foo'==u'bar'
 
#Output : bar
d = {u'foo':'bar'}
print d['foo']

python2中,调用encode方法可以将任意类型的字符串转换为字节字符串,或使用decode将任意类型的字符串转换为文本字符串
在实际使用中,这容易使人迷惑并导致灾难,考虑下面的例子:
如下所示,下面这段代码报错了,在第一个encode之后,已经将字符串按照utf-8格式转换为字节字符串,由于还有一个encode过程,首先会存在一个隐式解码过程,将字节字符串先解码为文本字符串,
这里将会使用默认的隐式转换方式,即getgetdefaultencoding()得到的方式,这里为ascii编码,因此下面的语句相当于:

text_str.encode('utf-8').decode('ascii').encode('utf-8')
text_str = u'\u03b1 is for alpha'
 
# Traceback (most recent call last):
#   File "/Users/shixiaowen/python3/python高级编程/字符串与unicode/python2字符串.py", line 48, in <module>
#     print text_str.encode('utf-8').encode('utf-8')
# UnicodeDecodeError: 'ascii' codec can't decode byte 0xce in position 0: ordinal not in range(128)
 
print text_str.encode('utf-8').encode('utf-8')

三、读取文件
python3:

文件总是存储字节,因此,为了使用文件中读取的文本数据,必须首先将其解码为一个文本字符串。
python3中,文本正常情况下会自动为你解码,所以打开或读取文件会得到一个文本字符串。
使用的解码方式取决系统,在mac os 或者 大多数linux系统中,首选编码是utf-8,但windows不一定。
可以使用locale.getpreferredencoding()方法得到系统的默认解码方式。

# <class 'str'>
# Python中有两种不同的字符串数据,文本字符串与字节字符串,两种字符串之间可以互相转换
# 本章将会学到文本字符串和字节字符串的区别,以及这两类字符串在python2和python3中的区别。
with open('字符串与unicode','r') as f:
    text_str=f.read()
    print (type(text_str))
    print (text_str)
 
import locale
#output : UTF-8
print (locale.getpreferredencoding())

读取文件时可以显示声明文件的编码,使用open方法的encoding关键字

# <class 'str'>
# Python中有两种不同的字符串数据,文本字符串与字节字符串,两种字符串之间可以互相转换
# 本章将会学到文本字符串和字节字符串的区别,以及这两类字符串在python2和python3中的区别。
with open('字符串与unicode','r',encoding='utf-8') as f:
    text_str = f.read()
    print(type(text_str))
    print(text_str)
 
"""
如果你希望以字节字符串的形式读取文件,使用如下的方式
"""
 
# <class 'bytes'>
# b'Python\xe4\xb8\xad\xe6\x9c\x89\xe4\xb8\xa4\xe7\xa7\x8d\xe4\xb8\x8d\xe5\x90\x8......
with open('字符串与unicode','rb') as f:
    text_str=f.read()
    print (type(text_str))
    print (text_str)

python2:

python2中,无论以何种方式打开文件,read方法总是返回一个字节字符串

# <type 'str'>
# Python中有两种不同的字符串数据,文本字符串与字节字符串,两种字符串之间可以互相转换
# 本章将会学到文本字符串和字节字符串的区别,以及这两类字符串在python2和python3中的区别。
with open('字符串与unicode','r') as f:
    text_str=f.read()
    print (type(text_str))
    print text_str

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值