【问题标题】:TypeError: not all arguments converted during string formatting 11TypeError:字符串格式化期间并非所有参数都转换了 11
【发布时间】:2015-03-30 14:58:19
【问题描述】:
def main():
    spiral = open('spiral.txt', 'r') # open input text file
    dim = spiral.readline() # read first line of text
    print(dim)
    if (dim % 2 == 0): # check to see if even
        dim += 1 # make odd

我知道这可能很明显,但我不知道发生了什么。我正在阅读一个只有一个数字的文件并检查它是否是偶数。我知道它被正确读取,因为当我调用它来打印dim 时,它会打印出10。但后来它说:

TypeError:字符串格式化期间并非所有参数都转换

对于我正在测试的行,以查看 dim 是否均匀。我确定这是基本的,但我无法弄清楚。

【问题讨论】:

    标签: python python-3.x


    【解决方案1】:

    文件对象的readline方法总是返回一个字符串;它不会为您将数字转换为整数。你需要明确地这样做:

    dim = int(spiral.readline())
    

    否则,dim 将是一个字符串,而执行 dim % 2 将导致 Python 尝试使用 2 作为参数执行字符串格式化:

    >>> '10' % 2
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: not all arguments converted during string formatting
    >>>
    

    另外,执行print(dim) 输出10 而不是'10',因为print 在打印时会自动删除撇号:

    >>> print('10')
    10
    >>>
    

    【讨论】:

      猜你喜欢
      • 2015-01-21
      • 2021-08-19
      • 1970-01-01
      • 2022-01-10
      • 2020-08-23
      • 2015-10-28
      • 2013-10-21
      相关资源
      最近更新 更多