简体   繁体   中英

String Comparison with a Format - Python

I wanted to check if user has entered the input in particular order or not. Basically i wanted user to input date in format like this

%d/%m/%y %H:%M

Is there any way i can compare string input with the above format in python?

import time
time.strptime("01/01/09 12:23", "%d/%m/%y %H:%M")

This will raise ValueError if the string doesn't match:

time.strptime("01/01/09 12:234", "%d/%m/%y %H:%M")
time.strptime("01-01-09 12:23", "%d/%m/%y %H:%M")

By the way, please don't bring back two-digit years--use %Y if at all possible.

This sounds like a job for... Regular Expressions! Have a look at the re module . What you want is simple enough that it would be fairly trivial to just hand you the regex for it, but you should learn to use them yourself.

OK, for this job, the strptime answer is better. But for the general case of making sure a string matches up with a format, regular expressions are generally the way to go.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM