Reputation: 173
I have a series of if statements in a function like this:
if time == "%%00":
#code
elif time == "%%15":
#code
elif time == "%%30":
#code
elif time == "%%45":
#code
Where time is 24 hour format ie. 0000-2400 and I'm checking what 15 interval time is at. All the statements are ignored however, so "%%interval" doesn't work. Is it just something simple I'm missing here or do I need a different method?
Upvotes: 0
Views: 83
Reputation: 13356
There are several ways to do it:
if time.endswith("00"):
#code
elif time[-2:] == "15":
#code
elif re.match(".{2}30", time):
#code
elif time.endswith("45"):
#code
Upvotes: 7
Reputation: 11130
fundamentally you are comparing string literals and nothing more, theres a couple ways of doing this, heres one without regular expressions.
if time[-2:] == "00":
#code
elif time[-2:] == "15":
#code
elif time[-2:] == "30":
#code
elif time[-2:] == "45":
#code
[-2:]
will grab the last two chars from the string
heres one with regular expression, Im not a big fan of them, they can generate subtle bugs, but thats just my opinion.
if re.match('..00', time):
#code
elif re.match('..15', time):
# code
elif re.match('..30', time):
# code
elif re.match('..45', time):
# code
the .
simply means match any char, except for \n
, re.match
either returns an object or None
if there was no match.
Upvotes: 0