0

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?

3
  • See the re module. Commented Jun 20, 2012 at 5:47
  • 2
    What in the world would make you think % is some kind of crazy string wildcard in Python (or that equality tests accept wildcards to begin with)? Commented Jun 20, 2012 at 5:50
  • I've been doing my first semester of sql at the same time and it uses % in statements such as WHERE str LIKE "%asd%". I thought it'd work similarly in python. Commented Jun 20, 2012 at 5:54

2 Answers 2

7

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
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.