2013-02-05 19 views

回答

2

我相信y你正在尋找類似於這個使用正則表達式。

注意在正則表達式"%%.*$"中,匹配從%%到行尾的所有內容。按照您的要求,如本例中所示,您的模式的多個實例將不會被視爲第一個模式將被替換,直到eol。

>>> st="""new in Python (and almost in programming). 

I have a file with some lines, for example 

... 

dr=%%dr 

mkl=%%mkl 

... 

I want to replace the %%dr and %%mkl with zeroes in order to have, for example 

...""" 
>>> lines = (re.sub("%%.*$","0",line) for line in st.splitlines()) 
>>> print '\n'.join(lines) 
new in Python (and almost in programming). 

I have a file with some lines, for example 

... 

dr=0 

mkl=0 

... 

I want to replace the 0 

... 
>>> 
+0

非常感謝。 。* $是關鍵, – user2042652

+0

您實際上不需要'$',因爲無論如何'。*'都會匹配直到行尾。 – georg

相關問題