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

如果您对程序有任何疑问,请在评论部分中提出。

更新日期:2019 年 8 月 27 日

504 次浏览

开启你的 职业生涯

完成课程后获得认证

开始
广告
© . All rights reserved.