stripping punctuation from tuples

Alex Martelli aleaxit at yahoo.com
Mon Mar 19 13:35:37 CET 2001


"Louis Luangkesorn" <lluang at northwestern.edu> wrote in message
news:3AB57F0C.594CF3E9 at northwestern.edu...
> How do you strip the punctuation from tuples?  In particular, say I have
> a tuple a[10] (which happened to come from a not very well designed
> database)
>
> >>> a[10]
> ('Alan Tsang',)

Note that, here, there is in fact no punctuation in the tuple a[10].
The parentheses and comma[s] are inserted by 'repr' (which is being
implicitly called by the interactive interpreter to show you the
results of expressions you type interactively).


> How do I get something to say 'Alan Tsang'  with out the parens or the
> ','

a[10][0], the first and only element of the tuple, has this value.


> Or, what I'm really trying to do is make this so
> >>>b = breakname(a[10])
> >>>b[0], b[1]
>
> 'Alan','Tsang'

If you know for sure that the tuple has exactly one item (or you
know it has at least one, and only care about the first one),

def breakname(atup):
    return atup[0].split()

To work for any number of items in the tuple, e.g.:

def breaknames(atup):
    return [ x for item in atup for x in item.split() ]

Of course, if you use repr (implicitly or explicitly) to view
the results of either function, you will see punctuation again,
since repr will insert it for clarity:-).


Alex







More information about the Python-list mailing list