NoahVerner
NoahVerner

Reputation: 875

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)

Upvotes: 0

Views: 1738

Answers (2)

DeepSpace
DeepSpace

Reputation: 81654

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

Upvotes: 1

shadow
shadow

Reputation: 878

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

Upvotes: 1

Related Questions