Python检查一个字符串是否存在于另一个字符串

2022-05-03 00:00:00 字符串 检查 是否存在

我需要执行的最常见的任务之一是检查一个字符串是否在一个字符串的列表中,本文介绍了两种方法实现。

"""
皮蛋编程(https://www.pidancode.com)
创建日期:2022/4/26
功能描述:Python检查一个字符串是否存在于另一个字符串
"""
addresses = ["123 Elm Street", "531 Oak Street", "678 Maple Street"]
street = "Elm Street"

# The top 2 methods to check if street in any of the items in the addresses list
# 1- Using the find method
for address in addresses:
    if address.find(street) >= 0:
        print(address)

# 2- Using the "in" keyword
for address in addresses:
    if street in address:
        print(address)

输出:

123 Elm Street
123 Elm Street

代码在Python3.9下测试通过。

相关文章