Too much code - slicing

Benjamin Kaplan benjamin.kaplan at case.edu
Thu Sep 16 21:47:49 CEST 2010


On Thu, Sep 16, 2010 at 3:35 PM, DataSmash <rdh at new.rr.com> wrote:
> I need to create a simple utility to remove characters from either the
> right or left side of directories.
> This works, but there has to be a better way.  I tried to use a
> variable inside the brackets but I can't get
> that to work.  Can anyone think of a way to do this with less code?
> Thanks!
>
> import os
>
> dirs = filter(os.path.isdir, os.listdir(''))
> for dir in dirs:
>
>    # Left side
<snip long if chain>

The int() type will convert a string to an int for you. So all you
need to do is check the side and slice accordingly.

if side=='l':
    code = dir[int(num):]
else :
    code = dir[:-1*int(num)]



More information about the Python-list mailing list