Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
270 views
in Technique[技术] by (71.8m points)

python - TypeError: not all arguments converted during string formatting

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:Python34hamcode.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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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]

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

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...