Reputation: 67
I have a list which contains string values taht represents calculations. From them I want to get a specific character, let's say plus and minus signs.
I tried using var1.find('a') != -1 or var.find('z') != -1
as suggested here Python: Using AND and OR with .FIND() method, but I'm still getting -1 when I try '-'.
Example:
lists = ["22 + 13", "4500 - 2"]
for list in lists :
if (list.find('+') or (list.find('-')) != -1) :
signpos = list.find("+") or list.find("-")
print(signpos)
else:
print('Error')
I get 3
aand -1
as results, where the desire output should be 3
and 5
.
What I'm not seeing?
Upvotes: 0
Views: 1889
Reputation: 33353
signpos = list.find("+") or list.find("-")
If the string does not have a plus sign, the first find()
call will return -1 which is a non-false value, so the second find()
will not be executed, and signpos will be assigned -1.
This probably isn't what you wanted.
Upvotes: 0
Reputation: 567
As others suggested, don't use list
as a variable name. It is a type.
lists = ["22 + 13", "4500 - 2"]
for string in lists:
signPos = None
if "+" in string:
signPos = string.find("+")
elif "-" in string:
signPos = string.find("-")
else:
print('Error')
print(signPos)
# Output
# 3
# 5
Upvotes: 1