[Python的]类型错误:无法格式化字符串转换期间,所有参数 [英] [Python]TypeError: not all arguments converted during string formatting

查看:1055
本文介绍了[Python的]类型错误:无法格式化字符串转换期间,所有参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有是应该计算海明code为偶校验有7位整数的程序,这里是该程序:

I have a program that's supposed to calculate Hamming Code for even parity with a 7-bit integer, here is the program:

data=list(input("Enter a 7-bit binary integer:"))

if (data[0]+data[1]+data[3]+data[4]+data[6])%2 == 0:
    data.insert(8, "0")
else:
    data.insert(8, "1")

if (data[0]+data[2]+data[3]+data[5]+data[6])%2 == 0:
    data.insert(7, "0")
else:
    data.insert(7, "1")

if (data[1]+data[2]+data[3])%2 == 0:
    data.insert(6, "0")
else:
    data.insert(6, "1")

if (data[4]+data[5]+data[6])%2 == 0:
    data.insert(3, "0")
else:
    data.insert(3, "1")

print("Your 7-bit binary integer with Hamming Code parity bits:",data)

然而,当我运行这个程序,我得到这个错误:

However, when I run this program I get this error:

Traceback (most recent call last):
  File "C:\Python34\hamcode.py", line 3, in <module>
    if (data[0]+data[1]+data[3]+data[4]+data[6])%2 == 0:
TypeError: not all arguments converted during string formatting

我不知道这意味着什么,以及如何解决它,任何答复将大大AP preciated。

I'm not sure what this means and how to fix it, any responses would be greatly appreciated.

谢谢!

推荐答案

类型数据是字符串列表,而不是一个整数列表:

The type of data is a list with strings, not a list of integers:

>>> data=list(input("Enter a 7-bit binary integer:"))
Enter a 7-bit binary integer:123456
>>> data
['1', '2', '3', '4', '5', '6']

因此​​,你试图连接字符串,并如预期你不总结数字:

As such, you're trying to concatenate strings and you're not summing numbers as expected:

if (data[0]+data[1]+data[3]+data[4]+data[6])%2 == 0:

要解决这个问题,你需要的所有字符串第一变成数字:

To fix it, you'll need to change all the strings into numbers first:

data = [int(x) for x in data]

目前,这条线在列表中添加字符串重新走到一起,以一个单一的字符串,你要使用字符串格式化该字符串(以%2 其语法字符串格式化)。操作是当应用于数模运算符,但它在应用到字符串中的字符串格式化操作符。

At the moment this line is adding the strings in the list back together to a single string and you're trying to use string formatting on that string (with % 2 which the syntax for string formatting). The operator % is the modulo operator when applied to a number but it's the string formatting operator when applied to a string.

在换句话说,你正在做的:

In other words, you're doing:

'123456' % 2

这意味着Python中试图插入 2 成字符串 123456 在适当的位置(这ISN ŧ可能的,因为没有指定为它的地方)。

which means Python is trying to insert that 2 into the string 123456 at the appropriate place (which isn't possible because there is no place designated for it).

这篇关于[Python的]类型错误:无法格式化字符串转换期间,所有参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆