首页 > 解决方案 > 当 python2 语句不再起作用时,在 python3 中打印一个 dict

问题描述

我的python2程序中有以下打印语句(在'-'符号之后)并用一些更复杂的python3代码(在'+'符号之后)替换它。有没有更好的更优雅的方式来做到这一点?

-                print("%(txn_processed)8d %(txn_skip)5d %(txn_ctr)5d")%accounts[account]
+                acc_ctrs = accounts[account]
+                processed = accounts[account]['txn_processed']
+                skipped = accounts[account]['txn_skip']
+                ctr = accounts[account]['txn_ctr']
+                print('%8d %5d %5d'%(processed, skipped, ctr))

字典帐户每个帐户有一个条目,子字典中有 3 个计数器。所以我在一个for account in accounts:循环中处理帐户并将 3 个计数器分为已处理、跳过和求和。这就是输出的样子(特别是最后两行):

           Output to ofx (GnuCash version)
TRANSACTIONS: 248
IN:           2018-008-transactions-30-12-to-26-09.csv
OUT:          2018-008-transactions-30-12-to-26-09.ofx
    accountnumber     processed  skip   sum
    NL89RABO0000000000      231     0   231
    NL71RABO1111111111        1    16    17

我对python3的了解有限。希望你们能帮帮我。

PS python2 行返回了关于 NoneType 和 Dict 的错误消息。

亲切的问候,古斯。

标签: python-3.x

解决方案


print是 python 3 中的一个函数,但你有混淆括号:

Python 2 的解释如下:

print ("%(txn_processed)8d %(txn_skip)5d %(txn_ctr)5d") % accounts[account]
#     ^----------------------- argument to print ---------------------------------------^

事实上,这些围绕字符串的括号在 python 2 中是完全不需要的。

Python 3 的解释是将括号视为参数,就像任何常规函数/方法一样:

print ("%(txn_processed)8d %(txn_skip)5d %(txn_ctr)5d") % accounts[account]
#     ^------------- argument to print --------------^

print返回None,您正试图调用__rem__它。这就是你有错误的原因。

为 Python 3 修复它所需要做的就是将所有内容都包含在括号中,而不仅仅是将要格式化的字符串:

print("%(txn_processed)8d %(txn_skip)5d %(txn_ctr)5d" % accounts[account])
#     ^------------- argument to print ---------------------------------^

推荐阅读