Federer
Federer

Reputation: 34775

Regex to Split 1st Colon

I have a time in ISO 8601 ( 2009-11-19T19:55:00 ) which is also paired with a name commence. I'm trying to parse this into two. I'm currently up to here:

import re
sColon = re.compile('[:]')

aString = sColon.split("commence:2009-11-19T19:55:00")

Obviously this returns:

>>> aString
['commence','2009-11-19T19','55','00']

What I'd like it to return is this:

>>>aString
['commence','2009-11-19T19:55:00']

How would I go about do this in the original creation of sColon? Also, do you recommend any Regular Expression links or books that you have found useful, as I can see myself needing it in the future!

EDIT:

To clarify... I'd need a regular expression that would just parse at the very first instance of :, is this possible? The text ( commence ) before the colon can chance, yes...

Upvotes: 2

Views: 3281

Answers (4)

ghostdog74
ghostdog74

Reputation: 342659

@OP, don't do the unnecessary. Regex is not needed with what you are doing. Python has very good string manipulation methods that you can use. All you need is split(), and slicing. Those are the very basics of Python.

>>> "commence:2009-11-19T19:55:00".split(":",1)
['commence', '2009-11-19T19:55:00']
>>>

Upvotes: 0

YOU
YOU

Reputation: 123881

You could put maximum split parameter in split function

>>> "commence:2009-11-19T19:55:00".split(":",1)
['commence', '2009-11-19T19:55:00']

Official Docs

S.split([sep [,maxsplit]]) -> list of strings

Return a list of the words in the string S, using sep as the
delimiter string.  If maxsplit is given, at most maxsplit
splits are done. If sep is not specified or is None, any
whitespace string is a separator and empty strings are removed
from the result.

Upvotes: 5

Steve Losh
Steve Losh

Reputation: 19882

>>> first, colon, rest = "commence:2009-11-19T19:55:00".partition(':')

>>> print (first, colon, rest)
('commence', ':', '2009-11-19T19:55:00')

Upvotes: 5

Ariel
Ariel

Reputation: 5830

Looks like you need .IndexOf(":"), then .Substring()?

Upvotes: 0

Related Questions