python中的字符串一直是困擾小編的一大難題茶凳,相信大家伙也曾體驗(yàn)過(guò)被各種編碼支配的恐懼吧。不過(guò)沒(méi)關(guān)系顷牌,相信你讀了這篇文章塞淹,一定會(huì)對(duì)python字符串豁然開(kāi)朗罪裹!
代碼鏈接:https://github.com/princewen/professional-python3
一、字符串類型
python3:
python語(yǔ)言有兩種不同的字符串套耕,一個(gè)用于存儲(chǔ)文本峡继,一個(gè)用于存儲(chǔ)原始字節(jié)。
文本字符串內(nèi)部使用Unicode存儲(chǔ)康愤,字節(jié)字符串存儲(chǔ)原始字節(jié)并顯示ASCII舶吗。
python3中,文本型字符串類型被命名為str检激,字節(jié)字符串類型被命名為bytes腹侣。
正常情況下傲隶,實(shí)例化一個(gè)字符串會(huì)得到一個(gè)str實(shí)例,如果希望得到一個(gè)bytes實(shí)例伦籍,需要在文本之前添加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中也有兩種字符串,不過(guò)洛二,python3中的str類在python2中名稱為unicode,但是,python3中的bytes類在python2中名稱為str類妓雾。
這意味著在python3中str類是一個(gè)文本字符串垒迂,而在python2中str類是一個(gè)字節(jié)字符串。
若不使用前綴實(shí)例化字符串楷拳,則返回一個(gè)str類(這里是字節(jié)字符串@艏椤!K臁)泊碑,如果想要得到一個(gè)文本字符串,需要在字符串前面加上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)
二沉桌、字符串轉(zhuǎn)換
python3:
可以在str與bytes之間進(jìn)行類型轉(zhuǎn)換留凭,str類包含一個(gè)encode方法,用于使用特定編碼將其轉(zhuǎn)換為一個(gè)bytes兼耀。于此類似求冷,bytes類包含一個(gè)decode方法,接受一個(gè)編碼作為單個(gè)必要參數(shù)拯坟,并返回一個(gè)str韭山。另一個(gè)需要注意的是冷溃,python3中永遠(yuǎn)不會(huì)嘗試隱式地在一個(gè)str與一個(gè)bytes之間進(jìn)行轉(zhuǎn)換,需要顯式使用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會(huì)在文本字符串和字節(jié)字符串之間嘗試進(jìn)行隱式轉(zhuǎn)換彪杉。
該工作機(jī)制是,如果解釋器遇到一個(gè)不同種類的字符串混合操作派近,解釋器首先會(huì)將字節(jié)字符串轉(zhuǎn)換為文本字符串洁桌,然后對(duì)文本字符串進(jìn)行操作。
解釋器在將字節(jié)字符串轉(zhuǎn)換為文本字符串的過(guò)程中使用隱式解碼谱轨,python2中默認(rèn)編碼幾乎總是ASCII.
我們可以使用sys.getdefaultencoding 方法來(lái)查看默認(rèn)編碼方式吠谢。
#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中,調(diào)用encode方法可以將任意類型的字符串轉(zhuǎn)換為字節(jié)字符串献汗,或使用decode將任意類型的字符串轉(zhuǎn)換為文本字符串
在實(shí)際使用中王污,這容易使人迷惑并導(dǎo)致災(zāi)難昭齐,考慮下面的例子:
如下所示,下面這段代碼報(bào)錯(cuò)了就谜,在第一個(gè)encode之后里覆,已經(jīng)將字符串按照utf-8格式轉(zhuǎn)換為字節(jié)字符串,由于還有一個(gè)encode過(guò)程篮奄,首先會(huì)存在一個(gè)隱式解碼過(guò)程,將字節(jié)字符串先解碼為文本字符串昼丑,
這里將會(huì)使用默認(rèn)的隱式轉(zhuǎn)換方式夸赫,即getgetdefaultencoding()得到的方式,這里為ascii編碼呼奢,因此下面的語(yǔ)句相當(dāng)于:
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高級(jí)編程/字符串與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:
文件總是存儲(chǔ)字節(jié)悴品,因此,為了使用文件中讀取的文本數(shù)據(jù)定枷,必須首先將其解碼為一個(gè)文本字符串届氢。
python3中退子,文本正常情況下會(huì)自動(dòng)為你解碼,所以打開(kāi)或讀取文件會(huì)得到一個(gè)文本字符串衣吠。
使用的解碼方式取決系統(tǒng)壤靶,在mac os 或者 大多數(shù)linux系統(tǒng)中,首選編碼是utf-8忧换,但windows不一定向拆。
可以使用locale.getpreferredencoding()方法得到系統(tǒng)的默認(rèn)解碼方式。
# <class 'str'>
# Python中有兩種不同的字符串?dāng)?shù)據(jù)刹缝,文本字符串與字節(jié)字符串,兩種字符串之間可以互相轉(zhuǎn)換
# 本章將會(huì)學(xué)到文本字符串和字節(jié)字符串的區(qū)別言疗,以及這兩類字符串在python2和python3中的區(qū)別噪奄。
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())
讀取文件時(shí)可以顯示聲明文件的編碼人乓,使用open方法的encoding關(guān)鍵字
# <class 'str'>
# Python中有兩種不同的字符串?dāng)?shù)據(jù),文本字符串與字節(jié)字符串碰缔,兩種字符串之間可以互相轉(zhuǎn)換
# 本章將會(huì)學(xué)到文本字符串和字節(jié)字符串的區(qū)別戳护,以及這兩類字符串在python2和python3中的區(qū)別。
with open('字符串與unicode','r',encoding='utf-8') as f:
text_str = f.read()
print(type(text_str))
print(text_str)
"""
如果你希望以字節(jié)字符串的形式讀取文件,使用如下的方式
"""
# <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中切蟋,無(wú)論以何種方式打開(kāi)文件榆芦,read方法總是返回一個(gè)字節(jié)字符串
# <type 'str'>
# Python中有兩種不同的字符串?dāng)?shù)據(jù)匆绣,文本字符串與字節(jié)字符串,兩種字符串之間可以互相轉(zhuǎn)換
# 本章將會(huì)學(xué)到文本字符串和字節(jié)字符串的區(qū)別堪夭,以及這兩類字符串在python2和python3中的區(qū)別拣凹。
with open('字符串與unicode','r') as f:
text_str=f.read()
print (type(text_str))
print text_str