Python:字串的分區與索引、字串的方法,

來源:互聯網
上載者:User

Python:字串的分區與索引、字串的方法,

這是關於Python的第3篇文章,主要介紹下字串的分區與索引、字串的方法。

字串的分區與索引:

字串可以用過string[X]來分區與索引。分區,簡言之,就是從字串總拿出一部分,儲存在另一個地方。

看下面這個例子,string[0]代表第一個字元,string[-1]為最後一個字元,空格也算一個字元;如果想截取某一段字元時,可以用string[X:X]來表示,其中冒號切記需為英文狀態下的,如果從頭或是從結尾開始截取,可以直接省略掉開頭和結尾的表示。

1 string = 'I am a Product Manager'2 print(string[0])3 print(string[2])4 print(string[-1])5 print(string[-3])6 print(string[0:9])7 print(string[4:])8 print(string[:9])

運行結果:

IargI am a Pr a Product ManagerI am a Pr

現在,我們來嘗試組一個新單詞:

1 string = 'father and mother, i love you'2 new_word = (string[0] + string[7] + string[11] + string[-10] +string[-8] + string[-3])3 print(new_word)

將分區分出來的字元組成了新單詞:family。運行結果:

family

字串的方法:

Python是物件導向的程式設計語言,面向的對象有各種功能特性,專業術語稱之為“方法”。看下面這個例子,將手機號碼保留後四位,其餘用“*”替換:

1 phone_number = '13098763773'2 hiding_phone_number = phone_number.replace(phone_number[:7],'*' * 7)3 print(hiding_phone_number)

裡面用到了替換這個方法:對象.replace(),可以將想要隱藏的手機位元用星號替換掉。運行結果:

*******3773

接下來,試試find(),尋找在字串裡第一個出現子串的位置。

1 search = '130'2 num_a = '13098763773'3 num_b = '13461309856'4 num_c = '15098763453'5 print(str(num_a.find(search)))6 print(str(num_b.find(search)))7 print(str(num_c.find(search)))

返回-1時,表示沒有查到。運行結果:

04-1

這一節,就先簡單介紹到這兒,關於Python的下一篇會介紹下函數。

作業環境:Python版本,3.6;PyCharm版本,2016.2;電腦:Mac

-----   End   -----

作者:杜王丹,公眾號:杜王丹,互連網產品經理。

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.