[Python Study Notes]字串操作

來源:互聯網
上載者:User

標籤:not   包含   字母   max   nbsp   style   串操作   gpo   round   

                      字串操作                                                                       

 

a.字串格式化輸出
1 name = "liu"2 print "i am %s " % name3    4 #輸出: i am liu  6 PS: 字串是 %s;整數 %d;浮點數%f
  b.尋找字串(find)
1 str.find(str, start=0, end=len(mystr))   # 檢測 str 是否包含在 mystr中,如果是返回開始的索引值,否則返回-1

 

1 >>> str = ‘xinge 好帥‘2  3 >>> str.find(‘xing‘)4 05  6 >>> str.find(‘好‘)7 6
  c.尋找替換字串中內容(replace)
1 mystr.replace(str1, str2, mystr.count(str1))  # 把 mystr 中的 str1 替換成 str2,如果 count 指定,則替換不超過 count 次.

 

1 >>> str = ‘abcabcabc‘2  3 >>> str.replace(‘a‘,‘xinge‘,2)4 ‘xingebcxingebcabc‘
  d.以str為分割符切片(split)
mystr.split(str=" ", 2) # 以 str 為分隔字元切片 mystr,如果 maxsplit有指定值,則僅分隔 maxsplit 個子字串

 

1 >>> str = ‘a\nb\tc‘2  3 >>> str4 ‘a\nb\tc‘5  6 >>> str.split()7 [‘a‘, ‘b‘, ‘c‘]
  f.將字串首字母大寫(capitalize)
1 >>> str=‘abc‘2  3 >>> str.capitalize()4 ‘Abc‘
g.把字串的每個單字首大寫(title)
1 >>> str = "hello world"2  3 >>> str.title()4 ‘Hello World‘
 h.startswith,endswith
1 startswith  # 檢查字串是否是以str 開頭, 是則返回 True,否則返回 False2 endswith  # 檢查字串是否以str結束,如果是返回True,否則返回 False.
  i.upper,lower
1 upper  # 轉換 mystr 中所有字元為大寫2 lower  # 轉換 mystr 中所有字元為小寫
  j.strip,lstrip,rstrip
1 strip  # 清除左右兩邊的空格2 lstrip  # 清除左邊的空格3 rstrip  # 清除右邊的空格
k.join
1 mystr.join(str)  # mystr 中每個字元後面插入str,構造出一個新的字串

 

                                                                           歡迎補充!                                                                

 

[Python Study Notes]字串操作

聯繫我們

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