Skip to content
Related Articles

Related Articles

Python – Check if string starts with any element in list

View Discussion
Improve Article
Save Article
  • Last Updated : 04 Aug, 2022
View Discussion
Improve Article
Save Article

While working with strings, their prefixes and suffix play an important role in making any decision. For data manipulation tasks, we may need to sometimes, check if a string starts with any of the matching strings. Let’s discuss certain ways in which this task can be performed.

Method #1 : Using filter() + startswith() Method 

The combination of the above function can help to perform this particular task. The filter method is used to check for each word and startswith() method tests for the prefix logic at target list. 

Python3




# Python3 code to demonstrate
# Prefix tests in Strings
# using filter() + startswith() method
 
# initializing string
test_string = "GfG is best"
 
# initializing prefix list
pref_list = ['best', 'GfG', 'good']
 
# printing original string
print("The original string : " + str(test_string))
 
# using filter() + startswith()
# Prefix tests in Strings
res = list(filter(test_string.startswith, pref_list)) != []
 
# print result
print("Does string start with any prefix list sublist ? : " + str(res))

Output : 

The original string : GfG is best
Does string start with any prefix list sublist ? : True

Method #2: Using startswith() Method 

As improvement to the above method, it is not always necessary to include filter method for comparison. This task can be handled solely by supplying a prefix check list as argument to startswith() method as well. 

Python3




# Python3 code to demonstrate
# Prefix tests in Strings
# using startswith()
 
# initializing string
test_string = "
GfG is best & quot
 
# initializing prefix list
pref_list = ['best', 'GfG', 'good']
 
# printing original string
print(& quot
       The original string : & quot
       + str(test_string))
 
# using startswith()
# Prefix tests in Strings
res = test_string.startswith(tuple(pref_list))
 
# print result
print(& quot
       Does string start with any prefix list sublist ? : & quot
       + str(res))

Output : 

The original string : GfG is best
Does string start with any prefix list sublist ? : True

Method #3: Using in operator

Python3




# Python3 code to demonstrate
# Prefix tests in Strings
 
# initializing string
test_string = "GfG is best"
 
# initializing prefix list
pref_list = ['best', 'GfG', 'good']
 
# printing original string
print("The original string : " + str(test_string))
 
res=False
x=test_string.split()
if(x[0] in pref_list):
    res=True
 
# print result
print("Does string start with any prefix list sublist ? : " + str(res))

Output

The original string : GfG is best
Does string start with any prefix list sublist ? : True

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!