Python基礎3切片,字串的方法,for 迴圈

來源:互聯網
上載者:User

標籤:arm   art   我是中國人   結束   string   error   相同   迴圈   cap   

切片:截取字串某一段字元,並不改變原字串。結構:[起始位置:終止位置:步長]  但不包括終止位置。所謂:顧頭不顧尾

索引:序列中每個元素都是有編號的,都是從0開始編號的。使用負數索引時,Python會從右邊開始數,第一個元素為-1.

如果你要截取的東西包括最左邊的元素。可以這樣寫:

word="我是中國人"print(word[:3])

結果:

我是中

倒取值(即取負值)切片:數字要從小向大寫,不能倒過來

例子

word="我是中國我人愛中國"print(word[-5:-2]) 注意:不能寫[-2:-5]

結果:

人我愛

字串方法:

1.capitalize 字串首字母大寫,其餘的全小寫。

 

s="abdeH,ehrDFG"print(s.capitalize())

 

結果:

Abdeh,ehrdfg

2.title字串 以特殊符號或者空格隔開,隔開的每一部分的首字母大寫,如果不隔開那就是一個字串的首字母大寫。其餘的全是小寫,與capitalize的不同是,capitalize特殊符號或者空格隔開的首字母不大寫

 

列子:

s="abdeH,ehrerG"b="sjhiHjkh"print("s",s.t)itle())print("b",b.title()

結果:

s Abdeh,Ehrergb Sjhihjkh

3. upper() 方法將字串中的小寫字母轉為大寫字母。這裡不舉例子了

4. lower() 方法將字串中的大寫字母轉為小寫字母。這裡不舉例子了

5.count(“某元素”,索引開始,索引結束)字串中某元素出現的個數,索引可以不寫。

s="abdeH,ehrerG"print("s",s.count("e"))

結果:

s 3

6.startswith 判斷是否以..開頭

  endswith 判斷是否以..結尾

例子:

s="abdeH,ehrerG"print("s",s.startswith("abde"))print("s",s.endswith("Gr"))print("s",s.endswith("rG"))

結果:

s Trues False   #s True   #注意這個和上個的不同

7.find 尋找某個元素的索引值   str.find(str, beg=0, end=len(string))。如果找不到顯示-1.

index 尋找某個元素的索引值   str.find(str, beg=0, end=len(string))。如果找不到顯示會報錯.

注意這兩個函數:如果字串中有多個相同的元素,只會得到最左邊的索引。
s="abdeH,ehrerG"print("s",s.find ("e"))print("s",s.index ("e"))print("s",s.index("tt"))

結果:

s 3Traceback (most recent call last):s 3  File "C:/Users/張守業/PycharmProjects/untitled/day1/聯絡.py", line 463, in <module>    print("s",s.index("tt"))ValueError: substring not found

8.strip() 方法用於移除字串頭尾指定的字元(預設為空白格)。只能一次去除頭部或尾部的某一項。

 rstrip() 刪除 string 字串右邊(right)的指定字元(預設為空白格).

 lstrip() 刪除 string 字串左邊(left)的指定字元(預設為空白格).

列子:

s="aabdeH,ehrerG"print("s",s.strip ("a",))print("s",s.strip ("G",))

結果:

s bdeH,ehrerGs aabdeH,ehrer

9.str.split(str="", num=string.count(str)).將字串分割成列表 

  • str -- 分隔字元,預設為所有的Null 字元,包括空格、換行(\n)、定位字元(\t)等。
  • num -- 分割次數。

例子:

s="aabdeH,ehrerG"print("s",s.split (",",1))

結果:

s [‘aabdeH‘, ‘ehrerG‘]

10. replace() 方法把字串中的 old(舊字串) 替換成 new(新字串),如果指定第三個參數max,則替換不超過 max 次。如果不指定第三個,則全部替換。

str.replace(old, new[, max])
例子:
s="我愛中國,中國中國"print("s",s.replace ("中國","我國",1))

結果:

 我愛我國,中國中國

 for 迴圈

不用for迴圈如何把一段字串中的每個元素列印出來?

seer="我愛中國我是中國人"count=0while count<len(seer):    print(seer[count])    count+=1

結果:

我愛中國我是中國人

 

Python基礎3切片,字串的方法,for 迴圈

聯繫我們

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