场景:
我有一个清单:
['item','place','thing']
我有一些字符串:
"item", "item1", "thing55", "place_C", "stuff", "junk5"
以上,我希望前四个匹配,后两个不匹配。startswith 函数最适合此检查。
(测试字符串“item”、“item1”等的列表不是python列表;它只是一组可能被检查的样本数据。但是,与“item”、“place”匹配的字符串列表"thing" 是代码中的 python 列表。)
我可以遍历第一个列表并将字符串与startswith进行比较:
successVar = False
for s in myStrings:
if (testString.startswith(s)):
successVar = True
break
# Now you would check successVar to decide if string matched
但这并不一定在所有情况下都最有效。例如,假设这是 if/elif 结构的一部分:
if (testString == "hello"):
# do something based on exact string match
elif (testString.endswith("!")):
# do something if string ends with _one_ specific entity
elif <somehow, do the above comparison in here>
# do something if string starts with any of the items in a list
else:
# do something if string didn't match anything
我想我可以将整个检查包装在一个函数中,但我觉得可能有一种方法可以更轻松或更简洁地使用内联代码来做到这一点。
这甚至可以在不制作功能的情况下完成吗?
谢谢