Comparing a string with multiple substrings of another string Comparing a string with multiple substrings of another string python python

Comparing a string with multiple substrings of another string


This should do the same thing as what you put.

return 'abcde'.startswith(input)


Don't name variables input, since it will shadow the builtin function input(). Its considered bad practice to do this, and easy enough to just choose another variable name.

You could use a set to check if the input matches any of the substrings:

lookups = {'a', 'ab', 'abc', 'abcd', 'abcde'}my_input = input()if my_input in lookups:    return True

We could also generate this set using a set comprehension:

characters = 'abcde'lookups = {characters[:i] for i in range(1, len(characters) + 1)}my_input = input()if my_input in lookups:    return True

For large sets of combinations, the benefit of using a set over a list is that you get constant time O(1) lookups for searching. This is much better than using a list, which will give you linear O(N) lookups.


There are multiple cute ways to do it. startwith is probably the most efficient one, but these should work too:

using lstrip:

return 'abcde'.lstrip(input)!='abcde'

using list comprehension:

return any(['abcde'[:i+1] == input for i in range(len('abcde'))])

using regex:

   pattern = re.compile('^'+input)   return bool(pattern.match('abcde'))

or just:

  return 'abcde'[:len(input)]==input