开发者

python: Detecting a negative number within a string

So I have a number of text files with a line like this:

STRT .M                 -9.0:  START DEPTH

I wish to detect the negative number and replace it with 0.1.

I can detect the negative number, simply by looking for the '-'

text.count('-')

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

My question is开发者_运维百科: How do I replace '-9.0' in the string that with the number 0.1? Ultimately, I want to output:

STRT .M                  0.1:  START DEPTH


The simple solution is to user .replace('-9.0','0.1') (see documentation for .replace()), but I think you need more flexible solution based on regular expressions:

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


Looks like you are working with LAS files. You can check out libLAS to see if it works for you. And here is a tutorial.


Regular expressions can do this:

>>> 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 documentation

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜