Python: detecting a negative number inside a string

So, I have some text files with a line like this:

STRT .M                 -9.0:  START DEPTH

I want to determine a negative number and replace it with 0.1.

I can detect a negative number just by looking at the '-'

text.count('-')

if text.count ('-')> 0, there is a negative number.

My question is: how to replace '-9.0' in line number 0.1? Ultimately, I want to deduce:

STRT .M                  0.1:  START DEPTH
+3
source share
3 answers

A simple solution for the user .replace('-9.0','0.1')( see the documentation for.replace() ), but I think you need a more flexible regex based solution:

import re
new_string = re.sub(r'-\d+\.\d+', '0.1', your_string)
+6
source

, LAS. libLAS, , . tutorial.

+4

:

>>> import re
>>> regex = re.compile(r' -\d+(\.\d+)?:')
>>> regex.sub(' 0.1:', 'STRT .M                 -9.0:  START DEPTH')
'STRT .M                 0.1:  START DEPTH'
>>> regex.sub(' 0.1:', 'STRT .M                 -19.01:  START DEPTH')
'STRT .M               0.1:  START DEPTH'
>>> regex.sub(' 0.1:', 'STRT .M                 -9:  START DEPTH')
'STRT .M                 0.1:  START DEPTH'

re.sub

+1

All Articles