《python核心程式設計》學習筆記(二) re

2021-08-09 10:07:48 字數 2194 閱讀 1318

1. match()函式從字串的開始部分開始匹配,匹配成功,則返回匹配物件;匹配不成功,則返回none。

>>> m = re.match('foo', 'on the table food')

>>> m

>>> none

2. search()函式用它的字串引數,在任意位置對給定的正規表示式模式

搜尋第一次出現的匹配情況。如果搜尋到成功的匹配,就會返回乙個匹配物件;否則,返回none。

>>> m = re.search('foo', 'seafood')

>>> print m

<_sre.sre_match object at 0x0000000002ad1c60>

>>> print m.group()

foo>>>

3. 萬用字元"."匹配除了'\n'以外的任何字元

4. 字符集類似於『|』

5. 匹配簡單郵箱

>>> patt = '\w+@(\w+\.)*\w+\.com'

>>> re.match(patt, 'nobdy@***.yyy.zzz.com')

<_sre.sre_match object at 0x00000000021e7558>

6. group()通常用於以普通方式顯示所有的匹配部分,但也能用於獲取各個匹配的子組。可以使用groups()方法獲取乙個包含所有匹配子字串的元組。

>>> m = re.match('(a(b))', 'ab')

>>> m.group()

'ab'

>>> m.group(1)

'ab'

>>> m.group(2)

'b'>>> m.group(0)

'ab'

>>> m.groups()

('ab', 'b')

>>>

注意:選取子組時,group()的引數可以是第幾個子組,但是groups()沒有引數,傳入位置引數會被當做*areg收集,

>>> m.groups()

('ab', 'b')

>>> m.groups(1)

('ab', 'b')

>>> m.groups(0)

('ab', 'b')

>>> m.groups(2)

('ab', 'b')

>>> m.groups()[0]

'ab'

7. findall()查詢字串中某個正規表示式模式全部的非重複出現情況,並返回乙個列表。若未找到匹配部分,則返回空列表 

對於乙個成功的匹配,每個子組匹配是由findall()返回的結果列表中的單一元素;對於多個成功的匹配,每個子組匹配時返回的乙個元組中的單一元素,而且每個元組是結果列表中的元素。

>>> re.findall(r'th\w+', 'this and that')

['this', 'that']

>>> re.findall(r'(\w+is) and (\w+at)', 'this and that')

[('this', 'that')]

>>> re.findall(r'(th\w+) and (th\w+)', 'this and that and the and three')

[('this', 'that'), ('the', 'three')]

>>> re.findall(r'(th\w+) and (\w+) and (th\w+)', 'this and that and the')

[('this', 'that', 'the')]

>>> re.findall(r'(th\w+)\w+(th\w+)\w+(th\w+)', 'this and that and the')

>>> re.findall(r'(th)\w+', 'this and that and the')

['th', 'th', 'th']

>>> re.findall(r'(th)\w+(th)\w+(th)\w+', 'this and that and the')

9. finditer()在匹配物件中迭代。

Python核心程式設計學習筆記(十一)

31 range 內建函式 1 range 的完整語法,要求提供兩個或三個整數引數 range start,end,step 1 range 會返回乙個包含所有k的列表,這裡start k end,從start到end,k每次遞增step。step不可以為零,否則將發生錯誤。range 2,19,3...

Python核心程式設計學習筆記(五)

for 語句 作用 用來遍歷可迭代物件的資料元素 可迭代物件是指能依次獲取資料物件的元素 可迭代物件包括 字串str 列表list 字典dict 集合set range函式返回的物件等 語法 for 變數列表 in 可迭代物件 語句塊 else 語句塊 range 函式 格式 見help range...

Python核心程式設計學習筆記(八)

集合set 集合是可變的容器 集合內的資料物件都是唯一的 不能重複多次 集合是無序的儲存結構,集合中的資料沒有先後順序關係 集合內的元素必須是不可變的物件 不能放列表字典 字典等可變物件 集合是可迭代物件 集合是相當於只有鍵,沒有值的字典 鍵則是集合的資料 建立空的集合 set 建立非空集合 s 集...