Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing a string with multiple substrings of another string

Is there another simpler way to write code that basically checks every character of the string 'abcde'

if input == 'a' or input == 'ab' or input == 'abc' or input == 'abcd' or input == 'abcde':     return True 
like image 846
vsc Avatar asked May 18 '20 02:05

vsc


People also ask

How do I check if a string contains multiple substrings?

You can use any : a_string = "A string is more than its parts!" matches = ["more", "wholesome", "milk"] if any(x in a_string for x in matches): Similarly to check if all the strings from the list are found, use all instead of any .

How do you find multiple substrings in a string in Python?

Using regular expressions, we can easily check multiple substrings in a single-line statement. We use the findall() method of the re module to get all the matches as a list of strings and pass it to any() method to get the result in True or False.

How do you compare substrings in Python?

Using the 'in' operator: The in operator is the easiest and pythonic way to check if a python string contains a substring. The in and not in are membership operators, they take in two arguments and evaluate if one is a member of the other. They return a boolean value.

How do I compare multiple string values in Python?

To compare a string to multiple items in Python, we can use the in operator. We have the accepted_strings list. Then we can use the in operator to check if facility included in the accepted_strings list. Since this is True , 'accepted' is printed.


1 Answers

This should do the same thing as what you put.

return 'abcde'.startswith(input) 
like image 185
duckboycool Avatar answered Sep 25 '22 20:09

duckboycool