Python Check If String Contains Certain Characters
Chapter:
Python
Last Updated:
30-05-2023 13:16:49 UTC
Program:
/* ............... START ............... */
#Using the in operator:
string = "Hello, World!"
characters = "lo"
if any(char in string for char in characters):
print("String contains at least one of the characters.")
else:
print("String does not contain any of the characters.")
# Using the any() function with a generator expression:
string = "Hello, World!"
characters = "lo"
if any(char in string for char in characters):
print("String contains at least one of the characters.")
else:
print("String does not contain any of the characters.")
# Using a loop:
string = "Hello, World!"
characters = "lo"
contains_characters = False
for char in characters:
if char in string:
contains_characters = True
break
if contains_characters:
print("String contains at least one of the characters.")
else:
print("String does not contain any of the characters.")
/* ............... END ............... */
Output
String contains at least one of the characters.
Notes:
-
All these approaches check if any of the characters in the given string are present in the target string. You can replace "lo" in the above examples with any set of characters you want to check for.