【发布时间】:2020-05-03 21:02:16
【问题描述】:
有没有一种方法或某种库可以让您轻松比较字符串?这很难解释,但这里有一个例子:
str = "Hi World!"
if str == "(Hello | Hi) World!":
print("You said either 'Hi World!' or 'Hello World!'")
在这个例子中(当然,它实际上不会起作用),如果字符串是 'Hi World!'或“Hello World!”,那么它将返回 True。我很确定它有一个名字,但我不确定它是什么。
【问题讨论】:
-
一个选项是
str.endswith('World!') -
正则表达式接近您的条件,即:
if re.match(r'(Hello|Hi) World!', str):
标签: python string if-statement formatting