Reputation: 931
So I'm making a function that basically checks if the string past the 0th element is an exclamation mark and the first element is the letter 'h'.
so example:
>>>f('h!')
True
>>>f('h!!!!!')
True
>>>f('!!!!!')
False
>>>f('!!!h')
False
i wanted to do this using list comprehension but i end up making the output a list with the first element being the truth value. My function is the following:
def f(s):
return s[0] == 'h' and [i == '!' for i in s[1:]]
this returns
>>>f('h!!')
[True]
What's wrong with the way i've done it? if i remove the brackets after the 'and', it raises a syntax error.
Upvotes: 1
Views: 54
Reputation: 304147
This is probably the fastest way
def f(s):
return s == "h" + "!" * (len(s) - 1)
Upvotes: 1
Reputation: 34146
Try printing the list comprehension part:
print [i == '!' for i in s[1:]]
you will get a list of booleans like
>>> [True, True, True]
So if you want to apply the AND operator (returns True
if all the elements are True
) to that list (so you get the correct result), you can use the all()
built-in function:
return s[0] == 'h' and all([i == '!' for i in s[1:]])
According to Python docs:
all(iterable): Return True if all elements of the iterable are true (or if the iterable is empty).
Edit:
As @thefourtheye commented, to avoid the list creation, you can pass a generator expression to all()
:
return s[0] == 'h' and all(i == '!' for i in s[1:])
Upvotes: 3
Reputation: 17871
Change to this:
s[0] == 'h' and all(i == '!' for i in s[1:])
all
returns True if all the elements of the generator expression inside are returning True.
Upvotes: 1