python學習之字串

來源:互聯網
上載者:User

標籤:存在   序列   art   color   split   意義   函數   元組   tar   

1.String類型:由零個或多個字元組成的有限序列

   註:在python中雙引號和單引號意義相同,都可用於表示字串。2.字串內建函數和操作符    strip()  移除空白,賦值給新的變數
a = ‘ sb ‘b = a.strip()print(b)

    split()  分割,字串分裂成多個字串組成的列表。

a = ‘a b c d‘b = a.split()print(b)

    len()  計算字串長度

a = ‘a b c d‘print(len(a))

    index()  索引,尋找元素的位置所在

a = ‘a b c d‘print(a.index(‘b‘))

   [start:end:step]  切片,從一個字串中擷取子字串

a = ‘a b c d‘print(a[0:5:1])

3.字串格式化:

    字串格式化是只按指定的規則串連、替換字串並返回新的符合要求的字串。    Python中格式化字串的運算式文法為:                  format_string % string_to_convert 或                  format_string % (string_to_convert1,string_to_convert2,...)
print("Hello %s, age:%d" % ("simon", 24))
     字串的格式化format()
s="hello {0},age {1}"    #{0},{1}是預留位置s1=s.format(‘simon‘,‘24‘)print(s1)

除了格式化符合,有時候需要調整格式化符號的顯示方法,輔助格式化符合可以滿足這些需求。

格式化字串中的固定內容除了字母、數字、標點符號等可顯示的字元,還可以包含 不可顯示字元。這種字元稱為 逸出字元。用‘r‘禁用逸出字元。

4.字串串連join()

li = ["a", "b"]l1 = "_".join(li)print(l1)

5.字串分割符spilt()和partition()

區別:split()傳進去的參數,分割後消失,輸出為列表           partition()傳進去的參數,分割後存在,輸出為元組splitlines()根據分行符號(\n)分割
a = ‘axbcd‘b = a.partition(‘x‘)d = a.split(‘x‘)print(b)     #(‘a‘, ‘x‘, ‘bcd‘)print(d)     #[‘a‘, ‘bcd‘]

6.id()查看字串或者數位記憶體位址

a = ‘simon‘b = id(a)print(b)    #2767282156912

 

 

 

   

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.