1. 程式人生 > >Python基礎(三):字符串和元組常用方法

Python基礎(三):字符串和元組常用方法

所有 列表 www. bsp 介紹 不改變 結果 範圍 target

字符串

在python中單引號和雙引號所表示的字符串並沒有區別,字符串具有不可變性,及所有操作均不改變原字符串的值。另外三個雙引號和單引號包起來的字符串可以換行寫入。

In [83]: ‘‘‘sss
    ...: ‘‘
    ...: ss‘‘‘
Out[83]: "sss\n‘‘\nss"

In [84]: """eee
    ...: eee‘"‘
    ...: """
Out[84]: eee\neee\‘"\‘\n

查找

find(object,[start,[stop]])方法,其中參數start和stop為可選參數,代表查找範圍。find()方法在找不到結果會返回-1,而不會報錯,這也是非常重要的一點。

In [78]: str1=hello python

In [79]: str1.find(p)
Out[79]: 6

In [80]: str1.find(z)
Out[80]: -1

In [81]: str1.find(l,0,2)
Out[81]: -1

In [82]: str1.find(l,0,3)
Out[82]: 2

index()方法和count()方法與列表使用方法一樣。具體方法可參照上一節https://www.cnblogs.com/austinjoe/p/9365331.html

修改

split(seq=None,maxsplit=-1)方法可以分割字符串,若方法裏不加參數默認按空格分割。maxsplit參數可以選擇分割次數,默認是全部分割。

In [85]: str1=hello python hello word!

In [86]: str1.split()
Out[86]: [hello, python, hello, word!]

In [87]: str1.split(o)
Out[87]: [hell,  pyth, n hell,  w, rd!]

In [88]: str1.split(o,2)
Out[88]: [hell,  pyth, n hello word!]

替換

replace()方法可以替換字符串中的值為令外一個,還可限制替換次數。

In [91]: str1=hello python hello word!

In [92]: str1.replace(hello,你好)
Out[92]: 你好 python 你好 word!

In [93]: str1.replace(hello,你好,1)
Out[93]: 你好 python hello word!

In [94]: str1            #str1值並未改變,字符串的不可變性
Out[94]: hello python hello word!

拼接

字符串的拼接是非常有趣的,方法也是很多的,我主要介紹幾種常用的方法。

1.“+”拼接

In [95]: str1=hello

In [96]: str2=python

In [97]: str1+str2
Out[97]: hellopython

2.join()方法

這個方法比較重要。列表和元組也可以使用,意義是把該字符串加到可叠代的對象中的每兩個元素之間。

In [98]: str1=***

In [99]: str1.join([hello,python])
Out[99]: hello***python

In [101]: str1.join((a,s,d))
Out[101]: a***s***d

3.%s占位符

In [102]: str1="%s我是誰?%s" % (,不知道)

In [103]: str1
Out[103]: 餵我是誰?不知道

4.format字符串格式化

In [104]: str1="{}你好".format(python)

In [105]: str1
Out[105]: python你好

元組

元組常用的有count()和index()。使用方法與之前所講的沒有差別。

In [107]: tup1=(a,w,e,r,r,w)

In [108]: tup1.count(w)
Out[108]: 2

In [109]: tup1.index(e)
Out[109]: 2

Python基礎(三):字符串和元組常用方法