Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python: Detecting a negative number within a string

Tags:

python

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
like image 264
Flux Capacitor Avatar asked Mar 20 '26 05:03

Flux Capacitor


1 Answers

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)
like image 63
Tadeck Avatar answered Mar 21 '26 19:03

Tadeck