2013-08-28 28 views
1

我在文本文件中有很多行。一行例如:等於在Python中登錄後打印字符串?

838: DEBUG, GD, Parameter(Player_Appearance_Model) = GaussianDistribution(0.28, 0.09) 

有人可以請告訴我如何打印等號後面的所有字符串(「=」)。例如,在上述情況下,輸出應該是「GaussianDistribution(0.28,0.09)」。

我試圖分割線和打印最後一個索引,但是,它給了我「0.09)」的答案,當然,這是不正確的。

+0

你等號或逗號分割?用等號分割應該給你正確的結果。 – Jerry

+0

如果字符串包含多個'='會怎麼樣? –

+0

@AshwiniChaudhary,幸運的是它不包含任何倍數= – Sanchit

回答

7

你並不需要一個正則表達式,只是split()它:

>>> s = "838: DEBUG, GD, Parameter(Player_Appearance_Model) = GaussianDistribution(0.28, 0.09)" 
>>> s.split(" = ")[1] 
'GaussianDistribution(0.28, 0.09)' 

或:

>>> s.split("=")[1].strip() 
'GaussianDistribution(0.28, 0.09)' 
3

您可以使用str.partition()

>>> s = "838: DEBUG, GD, Parameter(Player_Appearance_Model) = GaussianDistribution(0.28, 0.09)" 
>>> print s.partition('= ')[2] 
GaussianDistribution(0.28, 0.09) 

這是櫃面的數據有用你需要有另一個等號。

0

您也可以使用此:

def GetPart(s,part=1): 
    out = s.split('=')[part].strip()  #only '=', spaces will be removed 
    return out 

>>> s = 'abcd=efgh' 
>>> GetPart(s) 
>>> 'efgh' 
>>> s = 'abcd= efgh'      #note extra spaces 
>>> GetPart(s) 
>>> 'efgh' 
>>> s = 'abcd = efgh '    #even more space before/after 
>>> GetPart(s) 
>>> 'efgh' 

,當然還有:

>>> s = 'abcd=efgh'      
>>> GetPart(s,0)       #first part 
>>> 'abcd'