Saturday, November 23, 2024
Google search engine
HomeLanguagesPython program to check a string for specific characters

Python program to check a string for specific characters

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 = @neveropen%
           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 = "@neveropen123"
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 = "@neveropen123"
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 = "@neveropen%"
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)


Output

[True, True, True]

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 = "@neveropen%"
 
    res = re.compile(r'u')
 
    if res.findall(s):
        print("Character found")
    else:
        print("Character not found")


Output

Character not found

Method 5 : Using replace() and len() methods

Python3




# Check a string for specific character
s = "@neveropen123"
 
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 = "@neveropen%"
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)


Output

[True, True, True]

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 = "@neveropen123"
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.

RELATED ARTICLES

Most Popular

Recent Comments