python基礎5--字串

來源:互聯網
上載者:User

標籤:多個   imp   title   大小寫   wap   pac   with   strong   border   


1 find()、rfind()、index()、rindex()、count()

s = "this apple is red apple"s.find("apple")s.find("apple",9)s.find("apple",1,3) s.rfind("app") #從字串尾部向前尋找s.index("pp")s.count("p")

2 split()、rsplit()、partition()、rpartition()

partition將字串分為三部分,分隔字元前,分隔字元,分隔字元後,’r’表示從尾部向前

s.split(‘ ‘) #使用空格分割 [‘this‘, ‘apple‘, ‘is‘, ‘red‘, ‘apple‘]s.partition(‘ ‘)  #(‘this‘, ‘ ‘, ‘apple is red apple‘)

3 join()

多個字串串連,相鄰字串插入指定字元

s1 = s.split(‘ ‘)sep = "-"s2 = sep.join(s1) #‘this-apple-is-red-apple‘

4 lower()、upper()、capitalize()、title()、swapcase()

將字串轉換為小寫,大寫,首字母大寫,每個單字首大寫,大小寫互換

5 replace()

s.replace("apple","orange") #‘this orange is red orang‘

6 maketrans()、translate()

maketrans()產生字元對應表,translate()按照映射表替換字元,第二個參數為要刪除的字元

import stringtable = string.maketrans("abcdefg","1234567")s = "this apple is red apple"s.translate(table) #‘this 1ppl5 is r54 1ppl5‘s.translate(table,"hijk") #刪除hijk  ‘ts 1ppl5 s r54 1ppl5‘

7 strip()、rstrip()、lstrip()

刪除兩端、右端、左端空白字元或指定字元

s = "  abc   "s.strip() #刪除兩端空白字元 ‘abc‘"abdc".strip("a") #刪除指定字元"aabdcaaa".rstrip("a") #刪除右端指定字元  ‘aabdc‘

8 eval()

嘗試將任一字元轉化為運算式進行求值

eval("3+4")import matheval(‘math.sqrt(3)‘)

9 startswith()、endswith()

判斷字串是否以指定字串開始或結束

10 isalnum()、isalpha()、isdigit()、isspace()、isupper()、islower()

測試字串是否為數字或字母,是否為字母,是否為數字,是否為空白,大寫,小寫

python基礎5--字串

聯繫我們

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