I know how to cycle through all tuples in a list. However, my problem is to see if a string is in a tuple within the list. I have constructed the following:
# where:
unformatted_returns = [('2015-6-10', u'88.48'), ('2015-6-9', u'86.73'), ('2015-6-8', u'86.15'), ('2015-6-5', u'86.05')]
date_new = '2015-6-8'
for n in unformatted_returns: # The problem is here
if str(date_new) in n[0]:
print "found date"
rate_of_return_calc(date, date_new)
pass
else:
print "date {0} not found".format(date_new)
day_accumulater(d, m, y, date_new, date)
The problem is that the first tuple in the cycle n in unformatted_returns does not satisfy the condition, therefore it prints "not found". I don't want it do this obviously, because date_new is actually in the list!
So, how do I get the program to cycle through each n, then if all n's do not satisfy containing date_new then print "day not found"?
Move the
elseone level down.forloops also take anelsesuite, which is executed when you did not exit the loop early. Then add abreak:I've also cleaned up your test; you are matching
n[0]against a date string, you want them to be equal, not for one to be a substring of the other.Now one of two things can happen:
date_newis equal to the first element of one of the tuples. Thebreakis executed, theforloop ends, and theelsesuite is skipped.date_newis not equal to any of the first elements of the tuples. Thebreakis never executed, the loop ends and theelsesuite is executed to show no match was found.Demo:
This obviously would only ever find the first such matching element.
If you must process all matching elements, a flag is usually easiest:
All this assumes that
n[1]is of interest too. If all you need to know if the date is present, useany()and a generator expression to test for a matching element:Now we won't know which
nmatched, but that doesn't actually matter.