[Tutor] split or replace

Chris Fuller cfuller084 at thinkingplanet.net
Fri Jun 5 14:01:58 CEST 2009


On Friday 05 June 2009 06:18, Norman Khine wrote:
> Hello,
> What is the way to group each value so that I get a list, from a string
> like:
>
> dir = '/expert/forum/expert/expert'
> list = ['/expert', '/forum', '/expert', '/expert']
>
> I've tried:
> >>> dir = '/expert/forum'
> >>> dir.split('/')
>
> ['', 'expert', 'forum']
>
> >>> dir.replace("/expert","")
>
> '/forum'
>
> >>> dir = '/expert/forum/expert'
> >>> dir.replace("/expert","")
>
> '/forum'
>
> Thanks

Your code will be more portable if you use the os.path module.  I'd do 
something like this:

import os.path as osp
import os

path = '/bear/duck/gecko/toad'
l = []
b = True
a = path
sep = os.sep

while b:
    a,b = osp.split(a)
    l.append(osp.join(sep,b))

l.pop()
l.reverse()

print l
['/bear', '/duck', '/gecko', '/toad']

If you wanted something more consice, you could use a list comprehension:
['/'+i for i in path.split('/')]

Cheers


More information about the Tutor mailing list