[portland] Extracting strings from a tuple
Adam Lowry
adam at therobots.org
Sat Nov 3 00:02:56 CET 2007
On Nov 2, 2007, at 3:44 PM, Rich Shepard wrote:
> [(u'string 1', u'string 2', u'string 3', u'string 4', u'string 5',
> u'string
> 6', u'string 7')]
>
> What I want to do is walk through that tuple and extract each
> string.
> However, I cannot successfully slice it, iterate through it, or use
> an index
> to extract each string. According to "DIP," "Byte of Python," and
> other
> books I should be able to get each string as a separate item.
Since what you have is a list containing a tuple containing 7
strings, you need to first select which entry in the list you want,
then which entries in the tuple you want:
>>> l = [(u'string 1', u'string 2', u'string 3', u'string 4',
u'string 5', u'string6', u'string 7')]
>>> l[0]
(u'string 1', u'string 2', u'string 3', u'string 4', u'string 5',
u'string6', u'string 7')
>>> l[0][1:3]
(u'string 2', u'string 3')
When dealing with databases you end up with this idiom a lot:
search_results = getStuffFromDB()
for row in search_results:
print "String 1:", row[0], "String 2:", row[1]
Does that answer your question?
Adam
More information about the Portland
mailing list