2017-04-12 34 views
0

试图自学Python和Sqlite,我的脑袋正在旋转。如何从结果中“清理”查询的输出以去除所有括号,逗号等等。还想.title()第二栏。例如:清理Python中的sqlite查询

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) 

结果在下面的输出:

The birthdays we know about are: 
(1, 'joe smoe', '12-12-1212') 

一个人如何去重新格式化那些乱七八糟的东西,如:

The birthdays we know about are: 
1. Joe Smoe 12-12-1212 

我的最终目标是建立一个盘点系统为我的小企业,我的员工可以用来找到backstock项目位于我的库房。考虑使用Flask来做类似的事情,但是我离这个时间点还有很长的路要走。

回答

3

每一行是一个有三个元素的元组:号码,姓名和生日。 print(row)正在输出带有所有括号和引号的元组,而不是任何格式化的版本。

在Python中,你可以解构元组,并指定了它的部分不同的变量,然后格式化使用Python的语法printf样的格式:

for row in self.c.fetchall(): 
    number, name, date = row 
    print("%d. %s on %s" % (number, name.title(), date)) 

甚至:

for number, name, date in self.c.fetchall: 
    print("%d. %s on %s" % (number, name.title(), date)) 
+0

ZBW ,这工作很好。谢谢! – Biggen

1

当你print(row)你得到row的Python代表,其中包括引号和逗号等。你想要做的是将数据str.format到任何你喜欢的形状:

fmt = "{0}. {1}, on {2}" 
for row in self.c.fetchall(): 
    print(fmt.format(*row))