Search code examples
arrayspython-3.xlistanystartswith

How to check if a string starts with any char value from an array on Python?


Suppose that you have the following string:

the_string = '[({})]'

and suppose that you have the following array:

the_array = ['(','[','{']

How can you verify that the_string starts with any value from the_array?

I tried to create something like this:

if the_string.startswith(any x in the_array):
   print(True)
else:
   print(False)

But, it just didn't work, so I would like to know how could I get the a better approach to the solution (which in this case should be True)


Solution

  • any is a function, so

    if any(the_string.startswith(ch) for ch in the_array):
    

    If you are only going to print or return True or False you don't need the if and can use the output of any directly:

    print(any(the_string.startswith(ch) for ch in the_array))