作者dnoces (reverse)
看板Python
标题Re: [问题] 全文取代,第三问
时间Thu Sep 19 21:52:05 2013
借个标题
如果今天字串长这样
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)
1F:推 mars90226:re.sub(r'\d+', lambda m: ' ' * int(m.group(0)), str) 09/19 22:36
2F:→ mars90226:试了一下应该可以 09/19 22:36
谢谢m大
直接利用lambda方式传入match参数来取用
长见识了
※ 编辑: dnoces 来自: 114.33.206.104 (09/19 23:14)
3F:推 play9091:这方法,真的是长见识了……还可以这样子用! 09/22 16:03