There has to be a better way to split this string!

srinivas devaki mr.eightnoteight at gmail.com
Tue Feb 9 20:53:21 EST 2016


On Feb 10, 2016 6:56 AM, "Anthony Papillion" <anthony at cajuntechie.org>
wrote:
>
> -----BEGIN PGP SIGNED MESSAGE-----
> Hash: SHA512
>
> Hello Everyone,
>
> I am using datetime.now() to create a unique version of a filename.
> When the final file is named, it will look something like:
>
> myfile-2015-02-09-19-08-45-4223
>

You can easily do this(retrieving the tokens) using re module.

In [33]: mat =
re.search(r'(\S+)-(\d{4})-(\d{2})-(\d{2})-(\d{2})-(\d{2})-(\d{2})-(\d{4})',
'myfi-le-2015-02-09-19-08-45-4223')

In [34]: mat

Out[34]: <_sre.SRE_Match object; span=(0, 32),
match='myfi-le-2015-02-09-19-08-45-4223'>

In [35]: mat.groups() Out[35]: ('myfi-le', '2015', '02', '09', '19', '08',
'45', '4223')

In [36]: mat =
re.search(r'(\S+)-(\d{4})-(\d{2})-(\d{2})-(\d{2})-(\d{2})-(\d{2})-(\d{4})',
'myfile-2015-02-09-19-08-45-4223')
In [37]: mat

Out[37]: <_sre.SRE_Match object; span=(0, 31),
match='myfile-2015-02-09-19-08-45-4223'> In [38]: mat.groups()

Out[38]: ('myfile', '2015', '02', '09', '19', '08', '45', '4223')

if you don't want fiddle with regex you can use parse module(
https://github.com/r1chardj0n3s/parse). but why use an external library
when stdlib already provides it? :)

Regards
Srinivas Devaki
Junior (3rd yr) student at Indian School of Mines,(IIT Dhanbad)
Computer Science and Engineering Department
ph: +91 9491 383 249
telegram_id: @eightnoteight


More information about the Python-list mailing list