Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding a penultimate decimal in a string using python and regex

Tags:

python

regex

I have a python string:

text 5018.741043 57875.266717658247500  16.826  gbt  -chan 0 -subint 0 -snr 44.932

I know I can find 44.932 using:

r'.*(\b\d+\.\d+)'

But I want to find the penultimate \d+\.\d+ value, i.e. 16.826.

How can I do that please?


I have many lines similar to this example, but they may be slightly different in terms of spacing and number of characters, which is why I thought I should use regex.

Also, I ultimately want to substitute this value (here 16.826) for another number.

Thanks.

like image 221
user1551817 Avatar asked Jul 20 '26 19:07

user1551817


1 Answers

s = 'text 5018.741043 57875.266717658247500  16.826  gbt  -chan 0 -subint 0 -snr 44.932'

s.split(' ')[4]
# '16.826'

s.split(' ')[-1]
# '44.932'
like image 119
samredai Avatar answered Jul 23 '26 08:07

samredai



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!