Python 用循环替换子字符串
Python replacing substring with a loop
我正在使用一些任意表达式,例如 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("++", "+")
你检查字符串是否在 user_input
中的方式是错误的,因为
"--" or "+-" or "-+" or "++" in user_input
计算结果为真。
你需要做的
while any(string in user_input for string in ("--", "+-", "-+", "++")):
# Replacements.
您可以利用 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
我正在使用一些任意表达式,例如 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("++", "+")
你检查字符串是否在 user_input
中的方式是错误的,因为
"--" or "+-" or "-+" or "++" in user_input
计算结果为真。
你需要做的
while any(string in user_input for string in ("--", "+-", "-+", "++")):
# Replacements.
您可以利用 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