Python:TypeError:無法連接‘str’和‘int’對象我有一個python程序,它向整數添加字符串:a = raw_input("Enter a: ")b = raw_input("Enter b: ")print "a + b as strings: " + a + b
a = int(a)b = int(b)c = a + b
str(c)print "a + b as integers: " + c我知道這個錯誤:Python: TypeError: cannot concatenate 'str' and 'int' objects如何向整數中添加字符串?
3 回答

開心每一天1111
TA貢獻1836條經驗 獲得超13個贊
有兩種方法可以解決最后一個問題引起的問題。print聲明。
屬性的結果。str(c)打電話給c正如@jamylak正確顯示的那樣,然后連接所有字符串,或者可以替換最后一個字符串。print簡單地說:
print "a + b as integers: ", c # note the comma here
在這種情況下
str(c)
是不必要的,可以刪除。
樣本運行輸出:
Enter a: 3
Enter b: 7
a + b as strings: 37
a + b as integers: 10
有:
a = raw_input("Enter a: ")
b = raw_input("Enter b: ")
print "a + b as strings: " + a + b # + everywhere is ok since all are strings
a = int(a)
b = int(b)
c = a + b
print "a + b as integers: ", c
添加回答
舉報
0/150
提交
取消