Python 如何检查一个字符串中是否存在多个字符串

Python 如何检查一个字符串中是否存在多个字符串

本文将介绍如何在Python中检查一个字符串中是否存在多个字符串。

match = ['a','b','c','d','e'] 
str = "Welcome to Tutorialspoint" 
print("The given string is") 
print(str) 
print("Checking if the string contains the given strings") 
print(match) 
if any(c in str for c in match): 
    print("True") 
else: 
    print("False") 

输出

上述示例的输出如下所示:

The given string is
Welcome to Tutorialspoint
Checking if the string contains the given strings
['a', 'b', 'c', 'd', 'e'] 15. 
True

示例2

在下面给出的示例中,我们采用的程序与上面相同,但我们采用了一个不同的字符串并进行检查 −

match = ['a','b','c','d','e']
str = "zxvnmfg"

print("The given string is")
print(str)

print("Checking if the string contains the given strings")
print(match)

if any(c in str for c in match):
   print("True")
else:
   print("False")

输出

上面示例的输出如下:

The given string is
zxvnmfg
Checking if the string contains the given strings
['a', 'b', 'c', 'd', 'e']
False

使用正则表达式

正则表达式在第二种方法中被使用。如果尚未安装,请导入re库并安装它。我们将使用正则表达式和re.findall()函数来查看在加载re库后是否存在任何字符串。

示例1

在下面给出的示例中,我们将一个字符串作为输入,并且多个字符串进行匹配,使用正则表达式检查这些多个字符串是否与该字符串匹配。

import re
match = ['a','b','c','d','e']
str = "Welcome to Tutorialspoint"

print("The given string is")
print(str)

print("Checking if the string contains the given strings")
print(match)

if any(re.findall('|'.join(match), str)):
   print("True")
else:
   print("False")

输出

上述示例的输出结果如下所示:

The given string is
Welcome to Tutorialspoint
Checking if the string contains the given strings
['a', 'b', 'c', 'd', 'e']
True

示例2

在给定的示例中,我们使用与上面相同的程序,但我们使用了一个不同的字符串并进行检查-

import re
match = ['a','b','c','d','e']
str = "zxvnmfg"

print("The given string is")
print(str)

print("Checking if the string contains the given strings")
print(match)

if any(re.findall('|'.join(match), str)):
   print("True")
else:
   print("False")

输出

上述示例的输出如下所示 −

The given string is
zxvnmfg
Checking if the string contains the given strings
['a', 'b', 'c', 'd', 'e']
False

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程