2013-11-22 44 views
0

我只是想在字符串的開始處添加(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.' 

什麼是去做最簡單的/最簡單的方法是什麼?

回答

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.' 
+0

@iCodez:我誤讀;我認爲這需要*一個或多個選項卡。糾正。 –

+0

啊。我正在研究're.sub',但不確定使用'\ 1'。謝謝! :) – sPaz

相關問題