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
Program to check if a string contains any special character
Given a string, the task is to check if that string contains any special character (defined special character set). If any special character is found, don't accept that string. Examples : Input: Geeks$For$GeeksOutput: String is not accepted. Input: Geeks For GeeksOutput: String is accepted Approach
14 min read
Python Program To Check If A String Is Substring Of Another
Given two strings s1 and s2, find if s1 is a substring of s2. If yes, return the index of the first occurrence, else return -1. Examples :Â Input: s1 = "for", s2 = "geeksforgeeks" Output: 5 Explanation: String "for" is present as a substring of s2. Input: s1 = "practice", s2 = "geeksforgeeks" Output
3 min read
Python | Ways to check string contain all same characters
Given a list of strings, write a Python program to check whether each string has all the characters same or not. Given below are a few methods to check the same. Method #1: Using Naive Method [Inefficient] Python3 # Python code to demonstrate # to check whether string contains # all characters same
5 min read
Python - Filter Tuples with Strings of specific characters
Given a Tuple List, extract tuples, which have strings made up of certain characters. Input : test_list = [('gfg', 'best'), ('gfg', 'good'), ('fest', 'gfg')], char_str = 'gfestb' Output : [('gfg', 'best'), ('fest', 'gfg')] Explanation : All tuples contain characters from char_str. Input : test_list
5 min read
Python Program To Remove all control characters
In the telecommunication and computer domain, control characters are non-printable characters which are a part of the character set. These do not represent any written symbol. They are used in signaling to cause certain effects other than adding symbols to text. Removing these control characters is
3 min read
Python - Extract range characters from String
Given a String, extract characters only which lie between given letters. Input : test_str = 'geekforgeeks is best', strt, end = "g", "s" Output : gkorgksiss Explanation : All characters after g and before s are retained. Input : test_str = 'geekforgeeks is best', strt, end = "g", "r" Output : gkorgk
4 min read
Splitting String to List of Characters - Python
We are given a string, and our task is to split it into a list where each element is an individual character. For example, if the input string is "hello", the output should be ['h', 'e', 'l', 'l', 'o']. Let's discuss various ways to do this in Python.Using list()The simplest way to split a string in
2 min read
Remove Special Characters from String in Python
When working with text data in Python, it's common to encounter strings containing unwanted special characters such as punctuation, symbols or other non-alphanumeric elements. For example, given the input "Data!@Science#Rocks123", the desired output is "DataScienceRocks123". Let's explore different
2 min read
Python program to Extract string till first Non-Alphanumeric character
Given a string, extract all the alphanumerics before 1st occurrence of non-alphanumeric. Input : test_str = 'geek$s4g!!!eeks' Output : geek Explanation : Stopped at $ occurrence. Input : test_str = 'ge)eks4g!!!eeks' Output : ge Explanation : Stopped at ) occurrence. Method #1 : Using regex + search(
4 min read
Python | K Character Split String
The problems and at the same time applications of list splitting is quite common while working with python strings. Some characters are usually tend to ignore in the use cases. But sometimes, we might not need to omit those characters but include them in our programming output. Letâs discuss certain
4 min read