I have a bunch of strings but I only want to keep the ones with this format:
x/x/xxxx xx:xx
What is the easiest way to check if a string meets this format? (Assuming I want to check by if it has 2 /'s and a ':' )
I have a bunch of strings but I only want to keep the ones with this format:
x/x/xxxx xx:xx
What is the easiest way to check if a string meets this format? (Assuming I want to check by if it has 2 /'s and a ':' )
try with regular expresion:
import re
r = re.compile('.*/.*/.*:.*')
if r.match('x/x/xxxx xx:xx') is not None:
print 'matches'
you can tweak the expression to match your needs
Use time.strptime to parse from string to time struct. If the string doesn't match the format it raises ValueError
.
If you use regular expressions with match you must also account for the end being too long. Without testing the length in this code it is possible to slip any non-newline character at the end. Here is code modified from other answers.
import re
r = re.compile('././.{4} .{2}:.{2}')
s = 'x/x/xxxx xx:xx'
if len(s) == 14:
if r.match(s):
print 'matches'