python筆記1 字串處理函式

2021-09-28 19:05:23 字數 3526 閱讀 8305

對於re.findall(),第三個引數預設為空

返回值為乙個列表

import re

data = re.findall(r'(.*?)'

,text,re.s)

''' (.*?)-->'()'標記乙個子表示式的開始和結束位置,

'.'表示除換行符以外的乙個字元,

『*』前面內容可以出現0次或多次,

『?』前面的內容(子表達)可以出現0次或1次

'''

如果不使用re.s引數,則只在每一行內進行匹配,如果一行沒有,就換下一行重新開始。

而使用re.s引數以後,正規表示式會將這個字串作為乙個整體,在整體中進行匹配(涉及到類似python』』』 『』'括起來的多行字串時候特別注意)。

返回值為乙個列表

原型:str.split(sep=none, maxsplit=-1)

第二個引數代表最大分割數

maxsplit預設為-1:即不指定最大分割數目的值。

maxsplit=1的話表示最多切1刀,最大分割數為2(根據從前往後找到的sep位置切1刀). 如果沒有找到sep,則不切分。

原型:str.rsplit(sep=none, maxsplit=-1)

區別 : 它是從後往前找

>>

> s =

'a,b,ced'

>>

> s.split(

',',1)

#最多從前往後以『,』切一刀

['a'

,'b,ced'

]>>

> s.rsplit(

',',1)

#最多從後往前以『,』切一刀

['a,b'

,'ced'

]>>

> t =

'1,2,3,4,5'

>>

> t.split(

',',2)

['1'

,'2'

,'3,4,5'

]>>

> t.split(

'6',2)

#找不到不切分

['1,2,3,4,5'

]

括號中沒有內容:相當於空格,即進行匹配 去除的空格

原型:str.strip([chars])

兩端去除:

str兩端匹配char,能匹配就刪除,不能匹配就下乙個char,如果下乙個char也無法匹配當前字元就終止**(兩端匹配不是同時的,可能是從左往右匹配一遍,再從右往左匹配一遍)**

>>

>

'1223aass321'

.strip(

'123'

)'aass'

>>

>

'1223aass321'

.strip(

'12'

)'3aass3'

>>

>

'1224aass321'

.strip(

'123'

)'4aass'

原型:str.lstrip([chars])
>>

>

'122324'

.lstrip(

'2')

'122324'

>>

>

'122324'

.lstrip(

'12'

)'324'

>>

>

'122324'

.lstrip(

'13'

)'22324'

左端去除

原型:str.rstrip([chars])

>>

>

' 123 '

.strip(

)'123'

>>

>

' 123 '

.lstrip(

)'123 '

>>

>

' 123 '

.rstrip(

)' 123'

原型:str.replace(old, new[, count])

>>

> s =

' 123\n'

>>

> s

' 123\n'

>>

> s.replace(

'\n',''

)' 123'

>>

> s

' 123\n'

原型:str.join(sequence)

sequence :要連線的元素序列(元素型別必須為字串型別)

通過str將sqeuence連線起來

>>

> seq =

('2019'

,'10'

,'19'

)>>

> s =

'-'>>

> s.join(seq)

'2019-10-19'

>>

> s.join(

'23'

)'2-3'

>>

>

'2'.join(

'abc'

)'a2b2c'

>>

>

原型:str.translate(table)

引數table為字元的字典表

>>

> intab =

'123456'

>>

> outtab =

'abcdef'

#intab與outtab需要等長,每個字元建立字典

>>

> transtab =

str.maketrans(intab,outtab)

#建立字典

>>

> s =

'2019-10-19-21:03'

>>

> s.translate(transtab)

'b0a9-a0-a9-ba:0c'

>>

> transtab

>>

>

type

(transtab)

<

class

'dict'

>

>>

>

python學習筆記1 字串

小點總結 sentence input input the sentence words sentence.split 同樣適用於任何其它分隔符 9.letters list word 可以直接將word變成乙個list,其中每個元素都是乙個字母 判斷一句話中是否有正讀反讀都一樣的單詞 senten...

python學習筆記1 字串拼接

較為常用的字串拼接手法主要為兩種 1.通過format函式,形如 name input 姓名 age input 年齡 salary input 工資 info information1 of 姓名 n 年齡 n 工資 n format name name age age salary salary...

Python筆記(二)字串

記憶體位址 字串為不可變型別,原先指向字串的位址是不可改變的 line he line copy line print id line 2607584542648 print id line copy 2607584542648 line she he print id line 260758458...