【问题标题】:Why is my Python code not using the .replace function correctly?为什么我的 Python 代码没有正确使用 .replace 函数?
【发布时间】:2021-01-27 07:23:55
【问题描述】:

我正在尝试为数值积分器编写程序。省略所有我知道我正确的步骤,这是我没有工作的步骤:

fcn = str(input("Enter your function in terms of x: "))
a = eval(input('Enter a: '))
b = eval(input('Enter b: '))
N = 10
for i in range(1,N):
        x = str(fcn.find('x'))
        height = eval(fcn.replace(x,str(i)))
        height += height

但是,这不会生成正确的高度。例如,如果我有: fcn 是 x, a 为 1, b 是 10, N为10; 而不是得到高度是 1,2,3,4,5,6,7,8,9,10 ...我得到 00,00,00,00,00,00,00,00,00,00。

我是 Python 的初学者。我知道我的代码中有很多 eval 和 str 函数,但这只是为了纠正 Python 不断给我的错误。

【问题讨论】:

  • 你做过调试吗?我建议阅读ericlippert.com/2014/03/05/how-to-debug-small-programs
  • 如果您只使用eval 来纠正其他错误,那么解决这些错误可能是最好的做法。
  • .find() 返回找到字符串的索引。因此,如果您的字符串是“x”并且您正在寻找“x”,它将返回零。
  • 请提供预期的MRE。显示中间结果与预期结果的偏差。我们应该能够将您的代码块粘贴到文件中,运行它并重现您的问题。您发布的程序挂起等待输入。不要指望我们提供测试数据:只需将您的 input 替换为引发问题的测试用例即可。
  • @Prune - OP 确实提供了输入和预期输出......当然,它可能更容易阅读。

标签: python replace str-replace numerical-integration


【解决方案1】:

find 返回字符串中“x”的第一个索引,这不是很有帮助。相反,只需将“x”替换为i,您将覆盖其中可能存在的任何 x。为了使这个可测试,您可以使用写入固定值的函数覆盖input。在现实世界的环境中,您的代码将位于一个函数内部,该函数本身位于一个可导入模块中,然后一个单独的测试脚本将在调用时模拟输入。但这暂时可以。

# mock `input` for test
input_script = ["x + 100", "1", "10"]
def input(text):
    return input_script.pop(0)

fcn = str(input("Enter your function in terms of x: "))
a = eval(input('Enter a: '))
b = eval(input('Enter b: '))
N = 10
for i in range(1,N):
    height = eval(fcn.replace("x", str(i)))
    print(height)

【讨论】:

    猜你喜欢
    • 2019-03-12
    • 2020-10-25
    • 2021-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-27
    • 1970-01-01
    相关资源
    最近更新 更多