beginners question about return value of re.split

John Machin sjmachin at lexicon.net
Fri Mar 21 21:34:27 CET 2008


On Mar 22, 2:53 am, klaus <k... at us.de> wrote:
> On Fri, 21 Mar 2008 10:31:20 -0500, Tim Chase wrote:
>
> <..........>
>
> Ok thank you !
>
> I think I got a bit lost in all the possibilities python has to offer.

IMHO you got more than a bit lost. You seem to have stumbled on a
possibly unintended side effect of re.split.

What is your underlying goal?

If you want merely to split on '-', use datum.split('-').

If you want to verify the split results as matching patterns (4
digits, 2 digits, 2 digits), use something like this:

| >>> import re
| >>> datum = '2008-03-14'
| >>> pattern = r'^(\d\d\d\d)-(\d\d)-(\d\d)\Z'
You may notice two differences between my pattern and yours ...
| >>> mobj = re.match(pattern, datum)
| >>> mobj.groups()
| ('2008', '03', '14')

But what are you going to do with the result? If the resemblance
between '2008-03-14' and a date is not accidental, you may wish to
consider going straight from a string to a datetime or date object,
e.g.

| >>> import datetime
| >>> dt = datetime.datetime.strptime(datum, '%Y-%m-%d')
| >>> dt
| datetime.datetime(2008, 3, 14, 0, 0)
| >>> d = datetime.datetime.date(dt)
| >>> d
| datetime.date(2008, 3, 14)

HTH,
John



More information about the Python-list mailing list