首頁  >  文章  >  後端開發  >  Python的字串索引和分片

Python的字串索引和分片

高洛峰
高洛峰原創
2016-10-19 16:14:421700瀏覽

1.字串的索引

給一個字串,可輸出任一個字符,如果索引為負數,就是相當於從後向前數。

>>> str="HelloWorld!"

>>> print str[0]

H

>>>> print str[-4]

r

>>>> strello

>>> print str[0]

H

>>> print str[-4]

r

2.字串的分片

分片就是從給定的字串中分離出部分內容。

>>> str="HelloWorld!"

>>> print str[0]

H

>>>> print str[-4]

r

:

>> print

ell

>>> print str[:-7]

Hell

>>> print str[5:]

World!

>> str="p="Ep="Ep=edHpedHEppedHpedH5> str="Har> str="Har> str[0]

H

>>> print str[-4]

r

>>> print str[1:4]

ell

>>> print[1:4]

ell

>>> print[1:4]

ell

>>> print[1:4] 7] Hell

>>> print str[5:]

World!

分片的擴展形式:

str[I,J,K]意思是從I到J-1,每隔K個元素索引一次,如果K為負數,就是按從由往左索引。

>>> print str[2:7:2]

loo

>>> print str[2:7:1]

lloWo

>>> print str[2:7: str[2:72]

loo

>>> print str[2:7:1]

lloWo

ord函數是將字元轉換為對應的ASCII碼值,而chr函數是將數字轉換為字元。例如:

>>> print ord('a')

97

>>> print chr(97)

a

>>>  

>>> print chr(97)

a

>>>

Python中修改字串只能重新賦值。

每修改一次字串就生成一個新的字串對象,這看起來好像會造成效率下降,其實,在Python內部會自動對不再使用的字串進行垃圾回收,所

以,新的物件重用了前面已有字串的空間。


字串格式化:

>>> "%d %s %d you!"%(1,"goujinping",8)

'1 goujinping 8 you!'

>

> %d %s %d you!"%(1,"goujinping",8)

'1 goujinping 8 you!'


陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn