简体   繁体   中英

Print string after equals to sign in Python?

I have lots of lines in a text file. One line for example:

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

Can somebody please tell me how to print all the string after the equals to sign ("="). For instance, in the above case, output should be "GaussianDistribution(0.28, 0.09)".

I tried to split the line and print the last index, however, it gives me "0.09)" answer, which is, of course, incorrect.

You don't need a regex, just split() it:

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

or:

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

You can use str.partition() :

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

This is useful incase the data you need has another equals sign in it.

You can also use this:

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'

and of course:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM