Python - 无法隐式地将“int对象转换为str”

时间:2014-10-13 20:04:04

标签: python

我正在尝试制作一个程序,将投票数据添加到文件中。

代码:

#test
import random
f = open("yob1963.txt","a") #Opens Yob1936
code1 = random.randint(111111, 999999)
code2 = random.randint(11111111, 99999999)
num = random.randint(1, 6)
if num == "1":
    party = "UKIP"
if num == "2":
    party = "Labour"
if num == "3":
    party = "Conservatives"
if num == "4":
    party = "Liberal Democrats"
if num == "5":
    party = "Monster Raving Loony Party"
if num == "6":
    party = "Anonnymous"
if input("Type NOCHANGE if you have no changes to make to your household or enter if you do:   ") == ("NOCHANGE"):
    #NOCHANGE exit ------------------------------------
    print("Thankyou for using vote information updater") 
else:
    name = input("Please enter you name")
    print("Ok " + str(name) + "Your codes are " + int(code1) + ", " + int(code2) + " and your party is " + str(party))
    f.write(name, ", ", code1, ", ", code2, ", ", party)
    f.close()

我收到错误:

Traceback (most recent call last):
  File "C:/Users/Alex/SkyDrive/School/L5/Computing/Random Vote/random_vote.py", line 24, in <module>
    print("Ok " + str(name) + "Your codes are " + int(code1) + ", " + int(code2) + " and your party is " + str(party))
TypeError: Can't convert 'int' object to str implicitly

我已尝试更改str(code1)int(code1)等,但没有解决方案。

请帮忙

3 个答案:

答案 0 :(得分:3)

我会将format用于此

print("Ok {} Your codes are {}, {} and your party is {}".format(name, code1, code2, party)

另请注意,您将在此处遇到问题

num = random.randint(1, 6)
if num == "1":

numint,您将其与str进行比较,您应该这样做

if num == 1:
# and similar for the other if statements

答案 1 :(得分:2)

错误消息很明显,当使用整数连接字符串时,您不能直接将字符串和整数粘在一起,您必须先将整数显式转换为字符串。试试这个:

print("Ok " + str(name) + "Your codes are " + str(code1) + ", " + str(code2) + " and your party is " + str(party))

答案 2 :(得分:0)

print("Ok {name} Your codes are {code1}, {code2} and your party is {party}"
      .format(**vars()))