Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check python string format?

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 ':' )

like image 871
user1487000 Avatar asked Feb 19 '13 20:02

user1487000


People also ask

What does .2f mean in Python?

A format of . 2f (note the f ) means to display the number with two digits after the decimal point. So the number 1 would display as 1.00 and the number 1.5555 would display as 1.56 .

What is format () in Python?

Python's str. format() technique of the string category permits you to try and do variable substitutions and data formatting. This enables you to concatenate parts of a string at desired intervals through point data format.


Video Answer


2 Answers

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

like image 140
kofemann Avatar answered Oct 20 '22 10:10

kofemann


Use time.strptime to parse from string to time struct. If the string doesn't match the format it raises ValueError.

like image 21
Ulas Keles Avatar answered Oct 20 '22 09:10

Ulas Keles