String Problem, What is it I don't understand?

Peter Abel p-abel at t-online.de
Fri Jan 17 03:01:04 EST 2003


"Mark McEahern" <marklists at mceahern.com> wrote in message news:<mailman.1042744894.21019.python-list at python.org>...
> > I would expect to get the month day and year from the following, but
> > day and year are null
> >
> > xxx = "01/17/03"
> > month = xxx[0:2]
> > print "month=",month
> > day = xxx[3:2]
> > print "day=",day
> > year = xxx[6:2]
> > print "year=",year
> 
> 1.  Look into slicing.
> 
>     >>> d = '01/02/2003'
>     >>> d[0:2]
>  '01'
>     >>> d[3:5]
>  '02'
>     >>> d[6:]
>     '2003'
> 
> 2.  There are better ways to parse date strings into dates.  On Linux, the
> time module has a strptime function.  Otherwise, you can use mx.DateTime (a
> third party package, search for it on google).
> 
> // m
> 
> -

I would try it with re, which comes on board with python:
So you can have your date in a string with other information in
various formats.

>>> import re
>>> d = 'you can write dates in various ways: e.g. 01/02/2003 or
01-1-2003 or even 1/2/20003 or ugly 1 2 2003'
>>> print re.findall(r'(\d+)[-/\s](\d+)[-/\s](\d+)',d)
[('01', '02', '2003'), ('01', '1', '2003'), ('1', '2', '20003'), ('1',
'2', '2003')]
>>> # if you need a special formatting do this
>>> map(lambda (m,d,y):'%02d,%02d,%4d'%(int(m),int(d),int(y)),re.findall(r'(\d+)[-/\s](\d+)[-/\s](\d+)',d))
['01,02,2003', '01,01,2003', '01,02,20003', '01,02,2003']
>>> # And if you need integers try the following
>>> map(lambda (m,d,y):(int(m),int(d),int(y)),re.findall(r'(\d+)[-/\s](\d+)[-/\s](\d+)',d))
[(1, 2, 2003), (1, 1, 2003), (1, 2, 20003), (1, 2, 2003)]
>>>

Regards,
Peter




More information about the Python-list mailing list