Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading