Re: [問題] 全文取代,第三問

看板Python作者 (reverse)時間12年前 (2013/09/19 21:52), 編輯推噓2(201)
留言3則, 2人參與, 最新討論串2/2 (看更多)
借個標題 如果今天字串長這樣 str1 = ':@7text' str2 = ':@13text' 想要把原字串裡的數字取代成空格數量 也就是 new_str1 = ':@ $text' # 多個一$號 + 7個空格 new_str2 = ':@ $text' # 多一個$號 + 13個空格 這樣子的話有辦法用() 取r'\1'來格式化字串嗎? 自己有試著想用下面的寫法來達成 但會造成Invalid conversion specification 而不能動 pattern = '([\d]+)' print re.sub(pattern, ('{0:>%s}'%r'\1').format('$'), str1 ) 請問寫法應該怎麼改才好? 還是有別的方法? 先謝過各位大大了!! -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 114.33.206.104 ※ 編輯: dnoces 來自: 114.33.206.104 (09/19 22:14)

09/19 22:36, , 1F
re.sub(r'\d+', lambda m: ' ' * int(m.group(0)), str)
09/19 22:36, 1F

09/19 22:36, , 2F
試了一下應該可以
09/19 22:36, 2F
謝謝m大 直接利用lambda方式傳入match參數來取用 長見識了 ※ 編輯: dnoces 來自: 114.33.206.104 (09/19 23:14)

09/22 16:03, , 3F
這方法,真的是長見識了……還可以這樣子用!
09/22 16:03, 3F
文章代碼(AID): #1IEm68DW (Python)
文章代碼(AID): #1IEm68DW (Python)