Python基礎教程(第3版)(我的問題)
阿新 • • 發佈:2018-12-08
ClosedObject OpenObject 問題: 1將while not name改為while not name or name.isspace()或while not name.strip() #不應該是and嗎? 2.如何判斷循 環是提前結束還是正常結束的呢?可在迴圈開始前定義一個布林變數並將其設定為False,再在跳 出迴圈時將其設定為True。這樣就可在迴圈後面使用一條if語句來判斷迴圈是否是提前結束的。 broke_out = False for x in seq: do_something(x) if condition(x): broke_out = True break do_something_else(x) if not broke_out: print("I didn't break out!") 第十章 P225 3. >>> emphasis_pattern = r'\*\*(.+?)\*\*' >>> re.sub(emphasis_pattern, r'\1', '**This** is **it**!') 'This is it!' 4. 程式碼清單10-10 找出發件人的程式 # find_sender.py import fileinput, re pat = re.compile('From: (.*) $') for line in fileinput.input(): m = pat.match(line) if m: print(m.group(1)) 可像下面這樣執行這個程式(假設電子郵件儲存在文字檔案message.eml中): $ python find_sender.py message.eml Foo Fie 對於這個程式,應注意如下幾點。 為提高處理效率,我編譯了正則表示式。 我將用於匹配要提取文字的子模式放在圓括號內,使其變成了一個編組。 我使用了一個非貪婪模式,使其只匹配最後一對尖括號(以防姓名也包含尖括號)。 我使用了美元符號指出要使用這個模式來匹配整行(直到行尾)。 我使用了if語句來確保匹配後才提取與特定編組匹配的內容。