简体   繁体   English

Python 替换 function 中的“搜索”参数是否有限制?

[英]Is there a limit on the "search for" argument in the Python replace function?

I am using Python to search and replace a string in a.txt file.我正在使用 Python 来搜索和替换 a.txt 文件中的字符串。 I need to replace the value 0.000001 (6 decimal places), the code does not replace this value but will replace 0.0001 (4 decimal places).我需要替换值 0.000001(小数点后 6 位),代码不会替换该值但会替换 0.0001(小数点后 4 位)。 Therefore, is there some limit on this input argument (see code below)?因此,这个输入参数是否有一些限制(见下面的代码)?

a0 = 0.000001
ka = 0.1
dt = 7
an = a0+ka*dt

with open('file.txt', 'r') as f:
    data1 = f.read()
    data1 = data1.replace(str(a0), str(an), 1)

with open ('file.txt', 'w', 1) as f:
    f.write(data1)

It is not a matter of "limit", but of numeric notation:这不是“限制”的问题,而是数字符号的问题:

>>> a0 = 0.000001
>>> print(a0)
1e-06
>>> a0 = 0.0001
>>> print(a0)
0.0001
>>>

The "0.000001" string read from file won't get replaced because the replace() method will be looking for "1e-06".从文件中读取的“0.000001”字符串不会被替换,因为replace()方法将寻找“1e-06”。 The same does not occur with "0.0001". “0.0001”不会发生同样的情况。

Format a0 as float , instead:a0格式化float ,而不是:

    ...
    data1 = data1.replace(str("%f" % a0), str(an), 1)
    ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM