Skip to content
Related Articles

Related Articles

Improve Article

Python program to check a string for specific characters

  • Last Updated : 23 Dec, 2020

Given 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:

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course

Input: s = @geeksforgeeks%
       arr[] = {'o','e','%'}
Output: [true,true,true]

Input: s = $geek
       arr[] = {'@','e','a','$'} 
Output: [false,true,false,true]

Method  #1: 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 in operator which returns a boolean value (either True or false).

Python3




# Python implementation to check string
# for specific characters
  
# 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']

Method #2: Alternative method

Python3




# Python implementation to check string for
# specific characters
  
# 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]



My Personal Notes arrow_drop_up
Recommended Articles
Page :