Home > Back-end >  How to check if a string starts with any char value from an array on Python?
How to check if a string starts with any char value from an array on Python?

Time:04-11

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)

CodePudding user response:

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))

CodePudding user response:

One way is to convert the_string to array, after which you do a for ... in loop to each item in the array.

list = the_string.split(separator)

for item in list:
    if item in the_array:
        return True
  • Related