【问题标题】:Python replacing substring with a loop [duplicate]Python用循环替换子字符串[重复]
【发布时间】:2020-10-08 09:37:25
【问题描述】:

我正在使用一些任意表达式,例如 6 ++++6 或 6+---+++9++5,并且需要将其解析为最简单的形式(例如 6+6 和 6-9+ 5) 为什么下面的代码会导致无限循环?从调试中我可以看到字符串正在成功更新,但就像没有重新评估条件一样。

while "--" or "+-" or "-+" or "++" in user_input:
        user_input = user_input.replace("--", "+")
        user_input = user_input.replace("+-", "-")
        user_input = user_input.replace("-+", "-")
        user_input = user_input.replace("++", "+")

【问题讨论】:

  • while "foo" or "bar" in str: 被评估为while ("foo") or ("bar" in str):。由于"foo" 是一个真值,它被评估为true 并且不评估左侧或条件

标签: python while-loop infinite-loop


【解决方案1】:

您检查字符串是否在user_input 中的方式是错误的,因为 "--" or "+-" or "-+" or "++" in user_input 评估结果为真。

你需要做的

while any(string in user_input for string in ("--", "+-", "-+", "++")):
    # Replacements.

【讨论】:

    【解决方案2】:

    您可以使用any,为您的while循环创建一个定义明确的中断条件:

    replacements = [
        ("--", "+"),
        ("+-", "-"),
        ("-+", "-"),
        ("++", "+")
    ]
    
    user_input = '6+---+++9++5'
    while any(pattern[0] in user_input for pattern in replacements):
        for pattern in replacements:
            user_input = user_input.replace(*pattern)
    print(user_input)
    

    输出:

    6-9+5
    

    【讨论】:

    • 我总是喜欢使用固定参数而不是手动编写每一行。 (objects, methods, values) 的列表非常精美实用,可以同时在多个项目上调用 getattr(obj, method)(value)。
    猜你喜欢
    • 2019-03-17
    • 2017-03-12
    • 2017-08-04
    • 2016-06-06
    • 1970-01-01
    • 2015-11-28
    • 1970-01-01
    • 2017-04-07
    • 1970-01-01
    相关资源
    最近更新 更多