Check python string format?

旧城冷巷雨未停 提交于 2019-11-29 08:29:28

问题


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


回答1:


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




回答2:


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'



回答3:


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



来源:https://stackoverflow.com/questions/14966647/check-python-string-format

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!