string split

Hartmann Schaffer hs at paradise.nirvananet
Sun Dec 24 00:18:59 EST 2000


In article <slrn94b2go.srm.jp at localhost.localdomain>,
Jacek =?iso-8859-2?Q?Pop=B3awski?= <jp at ulgo.koti.com.pl> wrote:
>I have string:
>
>s="one two <br> three"
>
>splitting it gives:
>
>['one', 'two', '<br>', 'three']
>
>but if string looks like that:
>
>s="one two<br> three"
>
>string.split(s) gives me:
>
>['one', 'two<br>', 'three']
>
>is it possible to split not by space (" ") but by "<" and ">" ?
>
>I need:
>
>['one two','<br>','three']
>
>How to do it in simple way?

did you check the manual?  split takes a second argument.  however,
you can split only on either '<' or '>', and the delimiter won't be
part of any of the arguments.  you would need to roll your own
function:

def mysplit(string):
    list1= split(string, '<')
    list1= [list1[0]] + map(lambda x: '<' + x, list1[1:])
    list2= map(lambda x: string.split(c, '>'), list1)
    list3= [ ]
    for s in list3:
        list3.append(map(lambda x: x+'>', s[:-1])+[s[-1]])
    return reduce(lambda x,y: x+y, list3, [ ]

should do the trick.  you could easily generalize that.

hs



More information about the Python-list mailing list