大話(huà)python字符串

一、字符串類(lèi)型

<b>python3:</b>

python語(yǔ)言有兩種不同的字符串,一個(gè)用于存儲(chǔ)文本,一個(gè)用于存儲(chǔ)原始字節(jié)。
文本字符串內(nèi)部使用Unicode存儲(chǔ),字節(jié)字符串存儲(chǔ)原始字節(jié)并顯示ASCII。

python3中,文本型字符串類(lèi)型被命名為str,字節(jié)字符串類(lèi)型被命名為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'>

<b>python2:</b>

python2中也有兩種字符串,不過(guò),python3中的str類(lèi)在python2中名稱(chēng)為unicode,但是,python3中的bytes類(lèi)在python2中名稱(chēng)為str類(lèi)。
這意味著在python3中str類(lèi)是一個(gè)文本字符串,而在python2中str類(lèi)是一個(gè)字節(jié)字符串。
若不使用前綴實(shí)例化字符串,則返回一個(gè)str類(lèi)(這里是字節(jié)字符串!!!),如果想要得到一個(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)換

<b>python3:</b>

可以在str與bytes之間進(jìn)行類(lèi)型轉(zhuǎn)換,str類(lèi)包含一個(gè)encode方法,用于使用特定編碼將其轉(zhuǎn)換為一個(gè)bytes。于此類(lèi)似,bytes類(lèi)包含一個(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')

<b>python2:</b>

與python3不同的是,python2會(huì)在文本字符串和字節(jié)字符串之間嘗試進(jìn)行隱式轉(zhuǎn)換。
該工作機(jī)制是,如果解釋器遇到一個(gè)不同種類(lèi)的字符串混合操作,解釋器首先會(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方法可以將任意類(lèi)型的字符串轉(zhuǎn)換為字節(jié)字符串,或使用decode將任意類(lèi)型的字符串轉(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')

三、讀取文件

<b>python3:</b>

文件總是存儲(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ū)別,以及這兩類(lèi)字符串在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ū)別,以及這兩類(lèi)字符串在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)

<b>python2:</b>

python2中,無(wú)論以何種方式打開(kāi)文件,read方法總是返回一個(gè)字節(jié)字符串

# <type 'str'>
# Python中有兩種不同的字符串?dāng)?shù)據(jù),文本字符串與字節(jié)字符串,兩種字符串之間可以互相轉(zhuǎn)換
# 本章將會(huì)學(xué)到文本字符串和字節(jié)字符串的區(qū)別,以及這兩類(lèi)字符串在python2和python3中的區(qū)別。
with open('字符串與unicode','r') as f:
    text_str=f.read()
    print (type(text_str))
    print text_str
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容