2

I'm currently making a discord bot, and one of it's commands involves pulling data from a SQL table, for this I'm using the AioOdbc module, which almost exactly the same as Pyodbc, with the only real difference being that it doesn't block in asynchronous functions.

Which outputs in this format.

[('Item1',),('Item2',)]

How can I have it output something which is a bit nicer to read? Possibly something like

Item1, Item2

Any help is appreciated!

1 Answers1

5

You can turn it into a string where every item is separated by a comma and space with this code:

itemString = ', '.join((item[0] for item in items))

Where items is the name of this: [('Item1',),('Item2',)]

If you need it to be able to take items out from nested lists with arbitrary depth, such as in this list: [('Item1', 'Item2', ('Item3')), ('Item4', 'Item5')], you can use this code:

from collections import Iterable

def flatten(nested):
    for element in nested:
        if isinstance(element, Iterable) and not isinstance(element, (str, bytes)):
            yield from flatten(element)
        else:
            yield element
Will Da Silva
  • 6,386
  • 2
  • 27
  • 52
  • Consider referencing the source for the `flatten` code. I believe the original author is David Beazley, see https://stackoverflow.com/a/40857703/4531270 for details. – pylang Aug 21 '17 at 16:14
  • I'm fairly certain I wrote that `flatten` code. David's answer was in November 2016, but I wrote the first part of my python toolkit package (where I copied this from) during the summer of 2016. I'll upvote David's answer though, as I think it's the best answer for that question. – Will Da Silva Aug 21 '17 at 16:27
  • To be clear, the link I posted is not David Beazley's post, it is mine (so don't upvote presuming it is his). I added the link here bc it gives the full reference from his Cookbook (3rd ed. circa 2013), the source from which I got the code. That said, I do not know the original author. If it is you, thank you for the recipe. – pylang Aug 21 '17 at 16:49