开发者

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 inpu开发者_如何学Ct 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜