Python程序从列表中查找输入字符串的所有紧密匹配项
在本教程中,我们将找到问题的解决方案。让我们看看问题出在哪里。我们有一个字符串列表和一个元素。我们必须从列表中找到字符串,这些字符串必须与给定元素紧密匹配。参见示例。
Inputs strings = ["Lion", "Li", "Tiger", "Tig"] element = "Lion" Ouput Lion Li
我们可以通过使用startswith 内置方法来实现。请参阅步骤以查找字符串。
初始化字符串列表和字符串。
遍历列表。
如果列表中的字符串以元素开头或元素以列表中的字符串开头
Print the string
示例
## initializing the string list strings = ["Lion", "Li", "Tiger", "Tig"] element = "Lion" for string in strings: ## checking for the condition mentioned above if string.startswith(element) or element.startswith(string): ## printing the eligible string print(string, end = " ") print()
如果您运行上述程序,
输出结果
Lion Li
如果您对该程序有任何疑问,请在评论部分中提及它们。