python:检测字符串中的负数

Flu*_*tor 3 python string

所以我有一些像这样的行的文本文件:

STRT .M                 -9.0:  START DEPTH
Run Code Online (Sandbox Code Playgroud)

我希望检测到负数并将其替换为0.1.

我可以通过寻找' - '来检测负数

text.count('-')
Run Code Online (Sandbox Code Playgroud)

如果text.count(' - ')> 0,则为负数.

我的问题是:如何用数字0.1替换字符串中的'-9.0'?最终,我想输出:

STRT .M                  0.1:  START DEPTH
Run Code Online (Sandbox Code Playgroud)

Tad*_*eck 6

简单的解决方案是用户.replace('-9.0','0.1')(请参阅文档.replace()),但我认为您需要基于正则表达式的更灵活的解决方案:

import re
new_string = re.sub(r'-\d+\.\d+', '0.1', your_string)
Run Code Online (Sandbox Code Playgroud)