【问题标题】:not all arguments converted during string formatting python在字符串格式化python期间并非所有参数都转换了
【发布时间】:2015-09-17 11:05:47
【问题描述】:

我正在编写一个脚本,它打印可被 3 XOR 整除的列表项,最后一个字符 ==4 但我收到一条错误消息:TypeError: not all arguments converted during string formatting 我是 Python 新手,可能错过了一些明显的东西。代码如下:

lijst = ["124576", "795834", "890432", "907251"]    
for j in lijst:
if j[-1]==4 ^ j%3 > 0  :
    print(j)

【问题讨论】:

  • 应该是int(j)%3。您想将% 用作数字而非字符串的运算符。

标签: python python-3.x xor


【解决方案1】:

首先,您需要将4 更改为'4',因为您的项目是字符串并将j 转换为j%3 中的int,您还需要在比较表达式中加上括号,因为@987654326 的precedence @ 高于 == 并且它会引发 TypeError 如果你想保留你的结果,你可以使用列表理解:

>>> [j for j in lijst if (j[-1]=='4') ^ (int(j)%3 > 0)]
['124576', '795834', '890432']

如果您只想打印结果,可以使用带有打印功能的常用循环。

【讨论】:

    猜你喜欢
    • 2014-10-05
    • 2022-01-10
    • 2013-03-07
    • 1970-01-01
    • 2015-01-21
    • 1970-01-01
    • 2021-08-19
    相关资源
    最近更新 更多