【问题标题】:how to get the formatted output如何获取格式化输出
【发布时间】:2013-12-20 06:10:55
【问题描述】:

您好,我正在使用 python 和 odbc 数据库,即 Microsoft 访问。我得到像

这样的输出
(u'EXPANDx TB', 12.0, 10.0, 11.0, 13.0, 0.0, 46.0)
(u'EXPANDx TB & GFATM', 1.0, 1.0, 0.0, 1.0, 0.0, 3.0)
(u'EXPANDx TB & NRHM', 0.0, 0.0, 1.0, 0.0, 0.0, 1.0)
(u'GFATM', 1.0, 1.0, 0.0, 0.0, 0.0, 2.0)
(u'WHO', 3.0, 7.0, 3.0, 5.0, 0.0, 18.0)
(u'GFATM & EXPANDx TB', 1.0, 0.0, 0.0, 0.0, 0.0, 1.0)

额外的术语“u”正在显示。我也使用了 join 函数,但得到了类似的错误

print ",".join(table1)
TypeError: sequence item 1: expected string or Unicode, float found
 please help me out with this. Thanks in advance. 


 #!/usr/bin/python
 import pyodbc

 db_file = r'''C:\Users\Basavaraj\Documents\C&DST.accdb'''
 user = ''
 password = ''
 odbc_conn_str = 'DRIVER={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=%s;UID=%s;PWD=%s' % \
            (db_file, user, password)
 conn= pyodbc.connect(odbc_conn_str)
 #for row in cursor.fetchall():
 #   print row[2]
try:
    cursor = conn.cursor()
    cursor.execute("select * from Table1")
    for table1 in cursor.fetchall():
    print ",".join(table1)

finally:
    conn.close()

`

【问题讨论】:

  • u'foo' 表示这是一个 unicode 对象。但是你能给出一些代码吗?查询结果可能是一个可迭代对象,可以使用for循环。
  • 试试print ','.join(map(str, table))
  • 感谢 falsetru 它帮助...

标签: python python-2.7 pyodbc


【解决方案1】:

只需将每个项目转换为string

print ",".join(str(i) for i in table1)

如果您想保持 unicode 项目不变,那么:

print ",".join(str(i) if not isinstance(i, unicode) else i for i in table1)

【讨论】:

  • 你不需要内部列表。
猜你喜欢
  • 1970-01-01
  • 2016-10-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-06-07
  • 2020-07-01
相关资源
最近更新 更多