Reputation: 295
Trying to self teach Python and Sqlite and my head is spinning. How does one 'clean up' the output of a query to get rid of all the brackets, commas, etc... from the result. Would also like to .title()
the 2nd column. For example:
def get_all_bdays(self):
print("\n" * 100)
print("The birthdays we know about are: ")
self.c.execute('SELECT * FROM birthdays')
for row in self.c.fetchall():
print(row)
Results in the following output:
The birthdays we know about are:
(1, 'joe smoe', '12-12-1212')
How does one go about reformatting that mess to something like:
The birthdays we know about are:
1. Joe Smoe 12-12-1212
My end goal is to create an inventory system for my small business that my employees can use to find where backstock items are located in my storeroom. Thinking about using Flask for something like that, but I'm a long way off from that point in time.
Upvotes: 0
Views: 725
Reputation: 962
Each row is a tuple with three values: the number, name, and birthday. print(row)
is outputting the tuple, with all its parentheses and quotes, not any formatted version.
In Python, you can deconstruct the tuple and assign the parts of it to different variables, then format using Python's syntax for printf
-like formatting:
for row in self.c.fetchall():
number, name, date = row
print("%d. %s on %s" % (number, name.title(), date))
or even:
for number, name, date in self.c.fetchall:
print("%d. %s on %s" % (number, name.title(), date))
Upvotes: 3
Reputation: 15320
When you print(row)
you are getting the Python representation of row
, which includes the quotes and commas and such. What you want to do is to str.format
the data into whatever shape you like:
fmt = "{0}. {1}, on {2}"
for row in self.c.fetchall():
print(fmt.format(*row))
Upvotes: 1