Reputation:
I just started to use python 3. I want to find specific characters inside a string that is part of a list. Here is my code:
num = ["one","two","threex"]
for item in num:
if item.find("x"):
print("found")
So, I want to print "found" if the character "x" is inside of one of the elements of the list. But when I run the code, it prints 3 times instead of one.
Why is printing 3 times? Can someone help me?
Upvotes: 4
Views: 7791
Reputation: 20414
You need to break
out of looping
through the strings
if 'x'
is found as otherwise, it may be found in other strings
. Also, when checking if 'x'
is in the string
, use in
instead.
num = ["one","two","threex"]
for item in num:
if "x" in item:
print("found")
break
which outputs
:
found
And if I modify the num
list
so that it has no x
in any of the elements:
num = ["one","two","three"]
then there is no output when running the code again.
But why was it printing
3
times before?
Well simply, using item.find("x")
will return
an integer
of the index
of 'x'
in the string
. And the problem with evaluating this with an if-statement
is that an integer
always evaluates to True
unless it is 0
. This means that every string
in the num
list
passed the test: if item.find("x")
and so for each of the 3
strings
, found
was printed. In fact, the only time that found
wouldn't be printed
would be if the string
began with an 'x'
. In which case, the index
of 'x'
would be 0
and the if
would evaluate to False
.
Hope this clears up why your code wasn't working.
Oh, and some examples of testing the if
:
>>> if 0:
... print("yes")
...
>>> if 1:
... print("yes")
...
yes
>>> if -1:
... print("yes")
...
yes
Upvotes: 0
Reputation: 787
find returns Index if found and -1 otherwise.
num = ["one","two","threex"]
for item in num:
if item.find("x"):
print item.find("x")
i hope that you got the solution from above post ,here you know the reason why
Upvotes: 0
Reputation: 1219
find() returns -1 if the character is not found in the string. Anything that is not zero is equal to True. try if item.find("x") > -1
.
Upvotes: 1
Reputation: 16224
You can use in
again for strings:
num = ["one","two","threex"]
for item in num:
if "x" in item:
print("found")
Think in Strings as a list of chars like "ext"
-> ['e', 'x', 't']
so "x" in "extreme"
is True
Upvotes: 0