Python program to check a string for specific characters
Last Updated :
15 Feb, 2023
Here, will check a string for a specific character using different methods using Python. In the below given example a string 's' and char array 'arr', the task is to write a python program to check string s for characters in char array arr.
Examples:
Input: s = @geeksforgeeks%
arr[] = {'o','e','%'}
Output: [true,true,true]
Input: s = $geek
arr[] = {'@','e','a','$'}
Output: [false,true,false,true]
Method 1: Check a string for a specific character using in keyword + loop
Traverse through the char array and for each character in arr check if that character is present in string s using an operator which returns a boolean value (either True or false).
Python3
# function to check string
def check(s, arr):
result = []
for i in arr:
# for every character in char array
# if it is present in string return true else false
if i in s:
result.append("True")
else:
result.append("False")
return result
# Driver Code
s = "@geeksforgeeks123"
arr = ['e', 'r', '1', '7']
print(check(s, arr))
Output['True', 'True', 'True', 'False']
Time Complexity: O(n), where n is the length of the arr list because it needs to iterate over every character in the list.
Auxiliary Space: O(n), as it creates a new list of results with the same length of the input list.
Method 2: Check a string for a specific character using list comprehension
This is the alternative way to get check a string for a specific character using list comprehension.
Python3
# function to check string
def check(s, arr):
# returns a list of booleans
result = [characters in s for characters in arr]
return result
# Driver Code
s = "@geeksforgeeks123"
arr = ['e', 'r', '1', '@', '0']
print(check(s, arr))
Output[True, True, True, True, False]
Method 3: Check a string for a specific character using find()
The string find() function returns the first occurrence of specified value.
Python3
s = "@geeksforgeeks%"
arr= ["o","e","%"]
new_list=[]
for i in arr:
if(s.find(i)>0):
new_list.append(True)
else:
new_list.append(False)
print(new_list)
Method 4: Check a string for a specific character using compile()
Regular expressions are compiled into pattern objects, which have methods for various operations such as searching for pattern matches or performing string substitutions. re.findall return all non-overlapping matches of pattern in string, as a list of strings.
Python3
import re
if __name__ == '__main__':
s = "@geeksforgeeks%"
res = re.compile(r'u')
if res.findall(s):
print("Character found")
else:
print("Character not found")
OutputCharacter not found
Method 5 : Using replace() and len() methods
Python3
# Check a string for specific character
s = "@geeksforgeeks123"
arr = ['e', 'r', '1', '@', '0']
length = len(s)
new_list = []
for i in arr:
x = s.replace(i, "")
if(length-len(x) >= 1):
new_list.append(True)
else:
new_list.append(False)
print(new_list)
Output[True, True, True, True, False]
Method 6 : Using Counter() function
Python3
from collections import Counter
s = "@geeksforgeeks%"
freq = Counter(s)
arr = ["o", "e", "%"]
new_list = []
for i in arr:
if i in freq.keys():
new_list.append(True)
else:
new_list.append(False)
print(new_list)
Time Complexity:O(N)
Auxiliary Space: O(N)
Method 7 : Here's another approach using the map() and set() function.
Python3
def check(s, arr):
return list(map(lambda x: x in set(s), arr))
s = "@geeksforgeeks123"
arr = ['e', 'r', '1', '7']
print(check(s, arr))
Output[True, True, True, False]
In this approach, map() function is used to iterate over the arr and check each character with the s string. The in operator returns a boolean value indicating whether the character is present in the string or not. The result of the map() function is a map object, which can be converted to a list using the list() function.
Time Complexity: O(n), where n is the length of the arr list because it needs to iterate over every character in the list.
Auxiliary Space: O(n), as it creates a new list of results with the same length of the input list.
Similar Reads
Check if string contains character - Python We are given a string and our task is to check if it contains a specific character, this can happen when validating input or searching for a pattern. For example, if we check whether 'e' is in the string 'hello', the output will be True.Using in Operatorin operator is the easiest way to check if a c
2 min read
Python - Extract String till all occurrence of characters from other string Given a string, the task is to write a Python program to extract till all characters from other strings are found. Input : test_str = "geeksforgeeks is best for all geeks", check_str = "freak"Output : geeksforgeeks is best for aExplanation : a is last letter in freak to be present in string. The str
11 min read
Python program to check if a given string is Keyword or not This article will explore how to check if a given string is a reserved keyword in Python. Using the keyword We can easily determine whether a string conflicts with Python's built-in syntax rules.Using iskeyword()The keyword module in Python provides a function iskeyword() to check if a string is a k
2 min read
Python program to check if lowercase letters exist in a string Checking for the presence of lowercase letters involves scanning the string and verifying if at least one character is a lowercase letter (from 'a' to 'z').Python provides simple and efficient ways to solve this problem using built-in string methods and constructs like loops and comprehensions.Using
2 min read
Python Program to find if a character is vowel or Consonant Given a character, check if it is vowel or consonant. Vowels are 'a', 'e', 'i', 'o' and 'u'. All other characters ('b', 'c', 'd', 'f' ....) are consonants. Examples: Input : x = 'c'Output : ConsonantInput : x = 'u'Output : VowelRecommended: Please try your approach on {IDE} first, before moving on t
5 min read