【发布时间】:2018-05-15 14:27:10
【问题描述】:
使用startswith() 和endswith() 函数可以传递字符串元组,如果任何元素匹配,则返回结果True 例如:
text_to_find = ("string_1", "string2")
test = "string_to_look_in"
if test.startswith(text_to_find ) == True:
print ("starts with one of the strings")
是否有类似的命令可以用于元组,用于在字符串中查找字符串 - 即元组中的字符串之一出现在文本中的任何位置。 (而不是例如使用 for 循环,在其中单独查看字符串中的每个项目)。
【问题讨论】:
-
我建议
if any(x in test for x in text_to_find):。测试布尔条件时不需要== True。 -
@khelwood “答案”是
if any(x in test for x in text_to_find) -
"..在文本中任何地方出现的元组中的一个字符串.."
-
@Jean-FrançoisFabre 你说的很对。直到发表评论后,我才注意到问题的“任何地方”部分。
-
但你已经明白了。
标签: python python-3.x