Python's qw

Fernando Perez fperez528 at yahoo.com
Fri May 16 13:08:00 EDT 2003


A Puzzled User wrote:

> 
> Since Python doesn't have qw, is the following a
> proper/usual way to simulate it?
> thanks.
> 
> 
>  >>> a = """sunflower
> tulip
> jasmine"""
> 
>  >>> string.split(a, "\n")
> ['sunflower', 'tulip', 'jasmine']

I really don't use this anymore, but I wrote it as part of my perl2python
bicycle training wheels when I switched.  These days, I just '..'.split() when
I need it.

Cheers,

f.

# perlish code follows...

# the types module in Python 2.1 doesn't know about unicode, so let's kludge
# around the problem a bit:
if sys.version_info[0:3] >= (2,2,0):
    StringTypes = types.StringTypes
else:
    StringTypes = (types.StringType,)

#----------------------------------------------------------------------------
def flatten(seq):
    """Flatten a list of lists (NOT recursive, only works for 2d lists)."""

    # bug in python??? (YES. Fixed in 2.2, let's leave the kludgy fix in).

    # if the x=0 isn't made, a *global* variable x is left over after calling
    # this function, with the value of the last element in the return
    # list. This does seem like a bug big time to me.

    # the problem is fixed with the x=0, which seems to force the creation of
    # a local name

    x = 0 
    return [x for subseq in seq for x in subseq]

#----------------------------------------------------------------------------
def qw(words,flat=0,sep=None,maxsplit=-1):
    """Similar to Perl's qw() operator, but with some more options.

    qw(words,flat=0,sep=' ',maxsplit=-1) -> words.split(sep,maxsplit)

    words can also be a list itself, and with flat=1, the output will be
    recursively flattened. Examples:

    >>> qw('1 2')
    ['1', '2']
    >>> qw(['a b','1 2',['m n','p q']])
    [['a', 'b'], ['1', '2'], [['m', 'n'], ['p', 'q']]]
    >>> qw(['a b','1 2',['m n','p q']],flat=1)
    ['a', 'b', '1', '2', 'm', 'n', 'p', 'q']    """

    if type(words) in StringTypes:
        return [word.strip() for word in words.split(sep,maxsplit)
                if word and not word.isspace() ]
    if flat:
        return flatten(map(qw,words,[1]*len(words)))
    return map(qw,words)

#----------------------------------------------------------------------------
def qwflat(words,sep=None,maxsplit=-1):
    """Calls qw(words) in flat mode. It's just a convenient shorthand."""

    return qw(words,1,sep,maxsplit)





More information about the Python-list mailing list