TypeError:在字符串格式化期间,并非所有参数都已转换 [英] TypeError: not all arguments converted during string formatting

查看:324
本文介绍了TypeError:在字符串格式化期间,并非所有参数都已转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个程序应该为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

我不确定这意味着什么以及如何解决它,任何答复将不胜感激.

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

推荐答案

data的类型是带有字符串的列表,而不是整数列表:

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中的适当位置(这是不可能的,因为没有为其指定位置).

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).

这篇关于TypeError:在字符串格式化期间,并非所有参数都已转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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