python字串的截取

來源:互聯網
上載者:User

標籤:str   技術分享   strong   而不是   key   gpo   字元   img   post   

python中字串中一般都會存在多個字元,如何進行截取呢

例如:name = ‘my name is jockey’

我們首先對這個字串進行編號,從0開始:

 

1.列印某個字元

>>> print(name[0])
m
>>> print(name[11])
j

2.列印其中一段字元

如果冒號一側為空白標識該側取到底,取值的時候遵循左閉右開原則,即:[  )

 >>> print(name[3:14])
name is joc

>>> print(name[6:])
e is jockey

 >>> print(name[:16])
my name is jocke
>>> print(name[:17])
my name is jockey

 3.反向截取

 反向截取時從右往左排序的時候是從-1開始而不是從0開始

成段列印時還是左閉右開,與正向保持一致

>>> print(name[-1])
y
>>> print(name[-6])
j

>>> print(name[-9:-1])
is jocke

 

 借鑒別處看來的一個有趣的練習:

“找出你朋友中的魔鬼”

 word = ‘friends‘

 find_the_evil_in_your_friends =  word[0] + word[2:4] + word[-3:-1]

 print(find_the_evil_in_your_friends)

執行結果為:fiend 魔鬼

python字串的截取

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.