python字串方法

來源:互聯網
上載者:User

標籤:word   log   space   seq   dir   索引   intern   bin   AMM   

本文參考自《python基礎教程 (第二版)》

操作 文法 舉例 結果

尋找子串

 

find("str")

1.返回子串所在位置的最左端索引

2.沒有找到返回-1

3.可以接受起始點和結束點參數,範圍左閉右開

title = "Monty Python‘s Flying Circus"

1.title.find("Monty")

   title.find("Python")

2.title.find("Zircus")

3.title.find(“Circus”, 0, 22)   #提供起始點和結束點

 

0

6

-1

-1

添加序列

"sep".join(seq)

1.split的逆方法

1.sep = "+"

 seq = ["1", "2", "3", "4", "5"]

 sep.join(seq)

2.sep = "/"

 dirs = ["", "usr", "bin", "env"]

" sep.join(dirs)

 

 

"1+2+3+4+5"

 

"/usr/bin/env"

分割序列

str.split("sep")

1.join的逆方法

1."1+2+3+4+5".split("+")

2."/usr/bin/env".split("/")

["1", "2", "3", "4", "5"]

["", "usr", "bin", "env"]

小寫字母 str.lower() 1."Trondheim Hammer Dance".lower() "trondheim hammer dance"
大寫字母 str.upper() 1."Trondheim Hammer Dance".upper() "TRONDHEIM HAMMER DANCE"
標題轉換 string.capwords()

1.import string

 string.capwords("that‘s all, folks")

 

"That‘s All, Folks"

替換 str.replace(old,new) 1."This is a test".replace("is", "ezz") ‘Thezz ezz a test‘

 

 

 

去除空格

 

 

str.strip()

1.去除兩側空格(不含內部)

2.指定需要去除的字元,將它們作為參數

1."        internall whitespace is kept    ".strip()

2."*** SPAM * for * everyone!!!  ***".strip(" *!")

"internall whitespace is kept"

"SPAM * for * everyone"

str.lstrip()

去除左側空格

1."        internall whitespace is kept    ".lstrip() "internall whitespace is kept    "

str.rstrip()

去除右側空格

1."        internall whitespace is kept    ".rstrip() "        internall whitespace is kept"

 

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.