如何通过打印语句从返回的列表结果中删除多余的字符

How to remove superfluous characters from returned list result by print statement

我有一个连接到数据库的小型应用程序。 我可以使用 raw_input 插入数据,然后我 select 查询 return 一些结果作为报告。

这是代码片段:

if user_input == 'Y':
    cursor.execute(SQLCommand, Values)
    cursor.execute(SQLCommand1)
    result = cursor.fetchall()
    print 'The total costs until now are '
    print result

这是输出:

The total costs until now are 
[(2061.1, )]

我只需要看到数字,没有任何特殊字符。我应该使用 pprint 吗?

谢谢

看起来返回的 result 是一个包含单个元组(())的列表([])。因此,对列表进行索引,然后对元组进行索引以获取所需的值:

print result[0][0]

输出中的[]表示result是一个列表。在列表内部,() 表示列表的单个元素是一个元组。如果您不熟悉列表和元组,您肯定需要在官方 Python 教程中阅读它们。这些是 Python 编程的基础。

有两种方法可以获得您想要的结果。

  1. 按行和列位置索引:

    print result[0][0]
    
  2. 按行位置和列名索引:

    print result[0]['total']
    

备注

如果您知道您只会从查询中得到一行,您也可以使用 fetchone() 而不是 fetchall():

result = cursor.fetchone()
print result['total']