Python中检查字符串中是否存在单词列表

Python中检查字符串中是否存在单词列表:

  1. 使用生成器表达式迭代列表。
  2. 检查字符串中是否包含每个单词。
  3. 如果所有元素都满足条件,则列表中的单词存在于字符串中。
list_of_words = ['fql', 'zadmei', 'com']

my_str = 'zadmei123'

# ✅ 检查字符串中是否存在列表中的任何单词
any_word_in_string = any(word in my_str for word in list_of_words)
print(any_word_in_string)  # 👉️ True

# ------------------------------------------------------

# ✅ 检查列表中的所有单词是否存在于字符串中
all_words_in_string = all(word in my_str for word in list_of_words)
print(all_words_in_string)  # 👉️ False

# ------------------------------------------------------

# ✅ 从列表中查找字符串中存在的单词
matching_words = [word for word in list_of_words if word in my_str]
print(matching_words)  # 👉️ ['zadmei']

Python中检查字符串中是否存在单词列表

第一个示例使用 函数来检查列表中的任何单词是否存在于字符串中。

list_of_words = ['fql', 'zidmea', 'com']

my_str = 'zidmea123'

any_word_in_string = any(word in my_str for word in list_of_words)
print(any_word_in_string)  # 👉️ True

if any_word_in_string:
    # 👇️ this runs
    print('Some of the words from the list are contained in the string')
else:
    print('None of the words from the list are contained in the string')

我们使用生成器表达式来遍历列表。

生成器表达式用于对每个元素执行某些操作或选择满足条件的元素子集。

在每次迭代中,我们使用 运算符检查当前单词是否包含在字符串中并返回结果。

in 运算符测试成员资格。 例如,如果 x 是 s 的成员,则 的计算结果为 True,否则计算结果为 False。

my_str = 'fql zadmei'

print('fql' in my_str)  # 👉️ True
print('another' in my_str)  # 👉️ False

如果我们需要检查列表中的任何单词是否包含在字符串中,忽略大小写,将两个字符串都转换为小写。

list_of_words = ['FQL', 'ZADMEI', 'COM']

my_str = 'zadmei123'

any_word_in_string = any(word.lower() in my_str.lower()
                         for word in list_of_words)
print(any_word_in_string)  # 👉️ True

函数将一个可迭代对象作为参数,如果可迭代对象中的任何元素为真,则返回 True。

如果条件为列表中的任何单词返回 True,则 函数短路并返回 True。

如果我们需要检查列表中的所有单词是否都包含在字符串中,请改用 函数。

list_of_words = ['fql', 'zadmei', 'com']

my_str = 'zadmei.com'

all_words_in_string = all(word in my_str for word in list_of_words)
print(all_words_in_string)  # 👉️ False

内置函数将可迭代对象作为参数,如果可迭代对象中的所有元素都为真(或可迭代对象为空),则返回 True。

如果我们需要从列表中查找字符串中包含的单词,请使用列表推导。

list_of_words = ['fql', 'zadmei', 'com']

my_str = 'zadmei 306'

matching_words = [word for word in list_of_words if word in my_str]
print(matching_words)  # 👉️ ['bobby']

用于对每个元素执行某些操作或选择满足条件的元素子集。

新列表仅包含字符串中包含的单词。

我们可以通过将两个字符串都转换为小写来执行不区分大小写的成员资格测试。

list_of_words = ['fql', 'zadmei', 'com']

my_str = 'ZADMEI 306'

matching_words = [word for word in list_of_words if word.lower()
                  in my_str.lower()]
print(matching_words)  # 👉️ ['zadmei']

方法返回字符串的副本,其中所有大小写字符都转换为小写。

将两个字符串都转换为小写或大写允许进行不区分大小写的比较。