startswith 函数 - 不正确的争论 - 不抛出错误
startswith function - incorrect arguements - not throwing error
谁能告诉我为什么这不会引发错误?当用户输入 http:// 时打印 True,输入 https:// 时打印 false。我完全不明白为什么它会起作用。
URL = input("Enter an URL address: ")
URL.startswith("http://" or "https://")
"http://" or "https://"
是一个布尔表达式,其计算结果为 "http://"
,因为这就是 or
语句的含义(因为 "http://"
是遇到的第一个 True-ish 值or
语句),你需要这样做:
URL.startswith("http://") or URL.startswith("https://")
此外,正如@ShadowRanger 所建议的,您可以通过将接受的起始字符串的元组传递给 startswith
方法来使它更短更快,然后它将 return True
如果元组中与字符串开头匹配的任何字符串:
URL.startswith(("http://", "https://"))
谁能告诉我为什么这不会引发错误?当用户输入 http:// 时打印 True,输入 https:// 时打印 false。我完全不明白为什么它会起作用。
URL = input("Enter an URL address: ")
URL.startswith("http://" or "https://")
"http://" or "https://"
是一个布尔表达式,其计算结果为 "http://"
,因为这就是 or
语句的含义(因为 "http://"
是遇到的第一个 True-ish 值or
语句),你需要这样做:
URL.startswith("http://") or URL.startswith("https://")
此外,正如@ShadowRanger 所建议的,您可以通过将接受的起始字符串的元组传递给 startswith
方法来使它更短更快,然后它将 return True
如果元组中与字符串开头匹配的任何字符串:
URL.startswith(("http://", "https://"))