Simple question to split

John Machin sjmachin at lexicon.net
Thu Nov 9 18:12:00 EST 2006


Matthias Winterland wrote:
> Hi,
>
> I have a simple question. When I read in a string like:
> a='1,2,3,4,5 6 7,3,4', can I get the list l=[1,2,3,4,5,6,7,3,4] with a
> single split-call?
>

Using str method split, no -- as documented [hint!], it provides only a
single separator argument.

Using re.split function, yes -- as documented [hint!], it allows a
pattern as a separator.

The required pattern is simply expressed as "space or comma":

| import re
| >>> re.split('[, ]', '1,2,3,4,5 6 7,3,4')
| ['1', '2', '3', '4', '5', '6', '7', '3', '4']
| >>> [int(x) for x in re.split('[, ]', '1,2,3,4,5 6 7,3,4')]
| [1, 2, 3, 4, 5, 6, 7, 3, 4]

Cheers,
John




More information about the Python-list mailing list