pythontext-search

Finding 9 characters before a particular string in Python


For example here I have a line '2020-08-12 13:45:04 0.86393 %contrastWeber' and I need to extract 9 characters before ' %contrastWeber' string in text file. So, here my answer will be '0.86393'. I don't understand how to do it in Python? please help

1


Solution

  • line = '2020-08-12 13:45:04 0.86393 %contrastWeber'
    
    position = line.index('%contrastWeber')
    
    if position >= 0:
        starting = position - 9
        if starting < 0:
            starting = 0
        ending = position
        print(line[starting : ending])
    else:
        print('is not found')