'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 1:[1]
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))
Solution 2:[2]
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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | DeepSpace |
