我有一些文本文件,其中有一行内容如下:
STRT .M -9.0: START DEPTH
我希望您能检测负数并将其替换为0.1。我可以通过查找“-”来检测负数。
text.count('-')
如果 text.count('-') > 0,则存在负数。
我的问题是:如何将字符串中的“-9.0”替换为数字0.1?最终,我想输出:
STRT .M 0.1: START DEPTH
我有一些文本文件,其中有一行内容如下:
STRT .M -9.0: START DEPTH
text.count('-')
STRT .M 0.1: START DEPTH
.replace('-9.0','0.1')
(请参阅.replace()
的文档),但我认为你需要基于正则表达式的更灵活的解决方案:import re
new_string = re.sub(r'-\d+\.\d+', '0.1', your_string)
.5
)。 - Tadeck正则表达式可以做到这一点:
>>> 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'