1. 程式人生 > 實用技巧 >Python內建資料結構---字串

Python內建資料結構---字串

字串就是一段文字,由一個個字元組成的有序序列,其中的字元是Unicode碼點表示的。

字串是不可變物件,可以用單引號、雙引號、三引號引起來的字元序列。

字串的定義

In [1]: s1='hello world'

In [2]: s1
Out[2]: 'hello world'

In [3]: s1="hello world"

In [4]: s1
Out[4]: 'hello world'

In [5]: s1='''let's go'''

In [6]: s1
Out[6]: "let's go"

In [7]: s1="let's go"

In [8]: s1
Out[8
]: "let's go"

轉義

In [11]: s1='let\'s go'

In [12]: s1
Out[12]: "let's go"

In [17]: s1='hello \n world'

In [18]: print(s1)
hello
 world
In [19]: s1=r'hello \n world'

In [20]: print(s1)
hello \n world

In [21]: s1=R'hello \n world'

In [22]: print(s1)
hello \n world

字串元素訪問

由於有序,所以可以使用索引訪問

In [24
]: s1="select * from mysql.user where user='root';" In [25]: s1 Out[25]: "select * from mysql.user where user='root';" In [26]: s1[2] Out[26]: 'l' In [27]: s1[1] Out[27]: 'e' ## 由於不可變,所以無法修改 In [28]: s1[7]='user' --------------------------------------------------------------------------- TypeError Traceback (most recent call last)
<ipython-input-28-4697b4dcb7df> in <module> ----> 1 s1[7]='user' TypeError: 'str' object does not support item assignment

迭代字串

In [29]: for i in s1:
    ...:     print(i)
    ...:     print(type(i))
    ...:

與其他型別函式結合使用

s1="select * from mysql.user where user='root';"

lst=list(s1)

print(lst)
['s', 'e', 'l', 'e', 'c', 't', ' ', '*', ' ', 'f', 'r', 'o', 'm', ' ', 'm', 'y', 's', 'q', 'l', '.', 'u', 's', 'e', 'r', ' ', 'w', 'h', 'e', 'r', 'e', ' ', 'u', 's', 'e', 'r', '=', "'", 'r', 'o', 'o', 't', "'", ';']
t1=tuple(s1)

print(t1)
('s', 'e', 'l', 'e', 'c', 't', ' ', '*', ' ', 'f', 'r', 'o', 'm', ' ', 'm', 'y', 's', 'q', 'l', '.', 'u', 's', 'e', 'r', ' ', 'w', 'h', 'e', 'r', 'e', ' ', 'u', 's', 'e', 'r', '=', "'", 'r', 'o', 'o', 't', "'", ';')

字串拼接

In [32]: "hello " + "world"
Out[32]: 'hello world'

In [33]: a="hello "

In [34]: b="world"

字串方法

join(iterable)合併字串元素

語法:'string'.join(iterable) -> str

使用string作為分隔符,將可迭代物件iterable連線起來,返回一個新的字串(其中可迭代物件iterable的元素必須都是字串)

In [39]: lst=['1','2','3']

In [40]: sep='+'

In [41]: sep.join(lst)
Out[41]: '1+2+3'

In [42]: print('\n'.join(lst))
1
2
3

join方法要求可迭代物件的元素必須是字串

In [43]: lst=list(range(3))

In [44]: print('\n'.join(lst))
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-44-9c134bf59c3c> in <module>
----> 1 print('\n'.join(lst))

TypeError: sequence item 0: expected str instance, int found

join方法要求可迭代物件的元素必須是簡單型別,不能是應用型別

In [45]: lst=['1',['1','2'],'3']

In [46]: print('+'.join(lst))
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-46-cd667ec468bd> in <module>
----> 1 print('+'.join(lst))

TypeError: sequence item 1: expected str instance, list found

字串分割----split

語法:split(sep=None,maxsplit=-1) -> list

按指定分割字串sep(預設是空白字元),從左至右進行分割。maxsplit為分割的次數,預設值:-1,表示遍歷整個字串

In [1]: path="/usr/bin/env"

In [2]: path="/usr/bin/env python"

In [3]: path.split()
Out[3]: ['/usr/bin/env', 'python']

In [4]: path.split('/')
Out[4]: ['', 'usr', 'bin', 'env python']

In [5]: str1="I'm a\t good student. "

In [6]: str1.split()
Out[6]: ["I'm", 'a', 'good', 'student.']

In [7]: str1.split(maxsplit=1)
Out[7]: ["I'm", 'a\t good student. ']

In [8]: str1.split(maxsplit=2)
Out[8]: ["I'm", 'a', 'good student. ']

In [9]: str1.split('\t',maxsplit=2)
Out[9]: ["I'm a", ' good student. ']

rsplit(sep=None, maxsplit=-1) -> list

按指定分割字串sep(預設是空白字元),從右至左進行分割。maxsplit為分割的次數,預設值:-1,表示遍歷整個字串

In [11]: str1.rsplit(' ',maxsplit=2)
Out[11]: ["I'm a\t good", 'student.', '']

In [12]: str1.rsplit(' a',maxsplit=2)
Out[12]: ["I'm", '\t good student. ']

注意:split方法分隔符不能為空串

In [10]: str1.rsplit('',maxsplit=2)
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-10-0d6b0425ee91> in <module>
----> 1 str1.rsplit('',maxsplit=2)

ValueError: empty separator

splitlines([keepends]) -> list

按照行分隔符(\r、\r\n、\n)來分割字串,keepends ܶ為是否保留行分隔符

In [22]: 'ab c\n\nde fg\rkl\r\n'.splitlines()
Out[22]: ['ab c', '', 'de fg', 'kl']

In [18]: str1
Out[18]: "I'm a\t good student. \nI'm good study."

In [19]: str1.splitlines()
Out[19]: ["I'm a\t good student. ", "I'm good study."]

In [20]: str1.splitlines(True)
Out[20]: ["I'm a\t good student. \n", "I'm good study."]

字串分割----partition

語法:partition(sep) -> (head,sep,tail)

按指定分隔符sep,從左至右將字串分割,返回頭、分隔符、尾三部分組成的三元組,如果沒有找到分隔符,就返回頭和兩個空字串組成的三元組

In [23]: str1="I'm a\t good student. "

In [24]: str1.partition('d')
Out[24]: ("I'm a\t goo", 'd', ' student. ')

In [25]: str1.partition('ood')
Out[25]: ("I'm a\t g", 'ood', ' student. ')

In [27]: str1.partition('hehe')
Out[27]: ("I'm a\t good student. ", '', '')

注意:partition方法分隔符不能為空串

In [26]: str1.partition('')
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-26-e93649150055> in <module>
----> 1 str1.partition('')

ValueError: empty separator

字串修改----replace

語法:replace(old,new[,count]) -> str

在字串中查詢指定子串old,並替換為新子串new,返回新字串。count為替換次數,預設時全部替換

In [28]: 'www.abc.bbc.com'.replace('bc','')
Out[28]: 'www.a.b.com'

In [30]: 'www.abc.bbc.com'.replace('bc','',1)
Out[30]: 'www.a.bbc.com'

字串修改----translate

translate方法和replace方法的不同之處,在於translate方法只能進行單字元替換,能夠同時替換多個字元,效率比replace高

translate函式需要一張轉換表,這張表指明瞭不同Unicode碼點之間的轉換關係。要建立轉換表,可對字串型別呼叫maketrans方法,該方法接受兩個引數:兩個長度相同的字串,指明瞭要將第一個字串中的每一個字元轉換成第二個字串中的對應字元。程式碼如下:

In [33]: str.maketrans('ab','py')
Out[33]: {97: 112, 98: 121}

這裡看到返回了Unicode碼點的對映關係。

In [34]: table=str.maketrans('ab','py')

In [35]: s1.translate(table)
Out[35]: 'www.pyc.yyc.com'

當使用maketrans方法的時候,可以傳入第三個引數,指定將哪些字串刪除,如

In [37]: table=str.maketrans('ab','py','c')

In [38]: table
Out[38]: {97: 112, 98: 121, 99: None}

In [39]: s1.translate(table)
Out[39]: 'www.py.yy.om'

字串修改----strip

語法:strip([chars]) -> str

從字串兩端去除指定字符集chars中的字元,如果chars沒有指定,則去除兩端的空白字元

In [41]: s1='\r \n \t hello world \n \t'

In [42]: s1
Out[42]: '\r \n \t hello world \n \t'

In [43]: s1.strip()
Out[43]: 'hello world'

In [44]: s2="I'm fine."

In [45]: s2.strip('I.')
Out[45]: "'m fine"

lstrip([chars])從左側開始

rstrip([chars])從右側開始

字串查詢-----find

語法:find(sub[,start[,end]]) -> int

在指定區間[start,end),從左至右,查詢子串sub,找到就返回索引,找不到返回-1

語法:rfind(sub[,start[,end]]) -> int

在指定區間[start,end),從右至左,查詢子串sub,找到就返回索引,找不到返回-1

In [46]: s1="I'm very very happy!"

In [47]: s1.find('very')
Out[47]: 4

In [48]: s1.find('very',5)
Out[48]: 9

In [49]: s1.find('very',5,10)
Out[49]: -1

In [50]: s1.find('very',-1)
Out[50]: -1

In [53]: s1.find('very',-11,-1)
Out[53]: 9

In [54]: s1.find('very',-1,-11)
Out[54]: -1

字串查詢-----index

語法:index(sub[,start[,end]]) -> int

在指定區間[start,end),從左至右,查詢子串sub,找到就返回索引,找不到返回值異常ValueError

語法:rindex(sub[,start[,end]]) -> int

在指定區間[start,end),從右至左,查詢子串sub,找到就返回索引,找不到返回值異常ValueError

In [56]: s1.index('very',5)
Out[56]: 9

In [57]: s1.index('very')
Out[57]: 4

字串查詢-----count

語法:count(sub[,start[,end]]) -> int

在指定區間[start,end),從左至右,統計子串sub出現的次數

In [58]: s1
Out[58]: "I'm very very happy!"

In [59]: s1.count('very')
Out[59]: 2

In [60]: s1.count('very',5)
Out[60]: 1

In [61]: s1.count('very',4)
Out[61]: 2

字串判斷

語法:endswith(suffix[, start[, end]]) -> bool

在指定區間[start,end),判斷字串是否以suffix結尾

In [80]: s1.endswith('very',4,14)
Out[80]: False

In [81]: s1.endswith('very',4,13)
Out[81]: True

In [82]: s1.endswith('very',4)
Out[82]: False

In [83]: s1.endswith('y',4,-1)
Out[83]: True

語法:startswith(prefix[, start[, end]]) -> bool

在指定區間[start,end),判斷字串是否以prefix開頭

In [72]: s1
Out[72]: "I'm very very happy!"

In [73]: s1.startswith('very',4,10)
Out[73]: True

In [75]: s1.startswith('')
Out[75]: True

字串判斷is

isalnum() -> bool ީ是否是字母和數字組成

isalpha() ީ是否是字母

isdecimal()是否只包含十進位制數字

isdigit() 是否全部數字(0~9)

isidentifier() 是否以字母和下劃線開頭,其他都是字母、數字、下劃線

islower() 是否全部小寫

isupper() 是否全部大寫

isspace() ީ是否只包含空白字元