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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With