【发布时间】:2019-10-11 12:48:31
【问题描述】:
我有以下情况:
string = "abc"
if (string[1] == "b" and string[2] == "c") or (string[1] == "c" and string[2] == "b"):
print("ERROR")
有没有办法以 Python 的方式缩短它?
我看到(string[1] == "b" and string[2] == "c") 是(string[1] == "c" and string[2] == "b") 的相反语句。也许我可以使用它?
【问题讨论】:
-
string[1] == "b" and string[2] == "c"不是string[1] == "c" and string[2] == "b"的相反语句。这是!(string[1] == "b" and string[2] == "c")或string[1] != "b" OR string[2] != "c" -
索引是否重要,或者您是否真的想检查
string中是否存在 substr "bc" 或 "cb" ? -
@Cid 抱歉,我的意思是只交换了“b”和“c”
-
@magnus question 对您的问题很重要
-
@magnus 我想检查字符串中是否存在子字符串“bc”或“cb”。但它们必须是第二个第三个字母
标签: python algorithm if-statement code-readability