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
Asked
Active
Viewed 117 times
-5
-
2Please do not post images of text. – Mateen Ulhaq Aug 20 '20 at 03:51
-
Why not just use a simple regex search: `"(.{9})%contrastWeber"` – paddy Aug 20 '20 at 03:52
-
Welcome! Give [this](https://stackoverflow.com/help/how-to-ask) a read for detail on asking questions. For more help here, I suggest you update your answer with text output of the above image, things you've tried, researched, and ultimately, a little more detail. – Jason R Stevens CFA Aug 20 '20 at 03:57
-
Convert the string to list using ```str.split(" ")``` and then find index of ```%contrastWeber``` in list. Then the text you want shall be at index 1 less than previous index you found. – thisisjaymehta Aug 20 '20 at 04:12
1 Answers
0
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')

Shaker al-Salaam
- 16
- 2