在标签和文本之间添加字符串

时间:2013-11-22 15:27:12

标签: python regex

我只想在字符串开头的(0或更多)标签后添加字符串。 即。

a = '\t\t\tHere is the next part of string.  More garbage.'

(插入Added String here.) 到

b = '\t\t\t Added String here. Here is the next part of string.  More garbage.'

最简单/最简单的方法是什么?

1 个答案:

答案 0 :(得分:4)

简单:

re.sub(r'^(\t*)', r'\1 Added String here. ', inputtext)

^插入符号匹配字符串的开头,\t一个制表符,其中应该有零个或多个(*)。括号捕获匹配的选项卡以便在替换字符串中使用,其中\1将它们再次插入到您需要添加的字符串前面。

演示:

>>> import re
>>> a = '\t\t\tHere is the next part of string.  More garbage.'
>>> re.sub(r'^(\t*)', r'\1 Added String here. ', a)
'\t\t\t Added String here. Here is the next part of string.  More garbage.'
>>> re.sub(r'^(\t*)', r'\1 Added String here. ', 'No leading tabs.')
' Added String here. No leading tabs.'