原文出處:html
https://stackoverflow.com/questions/13654168/typeerror-cant-convert-int-object-to-str-implicitly
python
1、問題
git
我在嘗試着寫一個文字遊戲,遇到了一個函數錯誤,這個函數實現的功能是:在你輸入完字符後,就會消耗你的技能分。剛開始時報錯信息顯示我在試圖用一個整數減去一個字符,對應代碼爲「balance - strength」,這個錯誤很明顯,所以我將其改成「strength = int(strength)」修復了... 可是如今我遇到了一個之前從未見過的錯誤(o(╯□╰)o我是一個新手),我不知道它試圖在告訴我什麼以及如何修復它。github
如下爲該函數對應的代碼:ide
def attributeSelection(): balance = 25 print("Your SP balance is currently 25.") strength = input("How much SP do you want to put into strength?") strength = int(strength) balanceAfterStrength = balance - strength if balanceAfterStrength == 0: print("Your SP balance is now 0.") attributeConfirmation() elif strength < 0: print("That is an invalid input. Restarting attribute selection. Keep an eye on your balance this time!") attributeSelection() elif strength > balance: print("That is an invalid input. Restarting attribute selection. Keep an eye on your balance this time!") attributeSelection() elif balanceAfterStrength > 0 and balanceAfterStrength < 26: print("Ok. You're balance is now at " + balanceAfterStrength + " skill points.") else: print("That is an invalid input. Restarting attribute selection.") attributeSelection()
如下爲運行此部分代碼後的報錯信息:函數
Your SP balance is currently 25. How much SP do you want to put into strength?5 Traceback (most recent call last): File "C:\Python32\APOCALYPSE GAME LIBRARY\apocalypseGame.py", line 205, in <module> gender() File "C:\Python32\APOCALYPSE GAME LIBRARY\apocalypseGame.py", line 22, in gender customizationMan() File "C:\Python32\APOCALYPSE GAME LIBRARY\apocalypseGame.py", line 54, in customizationMan characterConfirmation() File "C:\Python32\APOCALYPSE GAME LIBRARY\apocalypseGame.py", line 93, in characterConfirmation characterConfirmation() File "C:\Python32\APOCALYPSE GAME LIBRARY\apocalypseGame.py", line 85, in characterConfirmation attributeSelection() File "C:\Python32\APOCALYPSE GAME LIBRARY\apocalypseGame.py", line 143, in attributeSelection print("Ok. You're balance is now at " + balanceAfterStrength + " skill points.") TypeError: Can't convert 'int' object to str implicitly
(提問者報錯信息中涉及較多,部分爲其項目代碼文件。爲縮短報錯信息,我將提問者所提到的函數部分代碼粘貼到本機後,運行完對應的報錯信息以下)this
Your SP balance is currently 25. How much SP do you want to put into strength?5 Traceback (most recent call last): File "test.py", line 26, in <module> attributeSelection() File "test.py", line 20, in attributeSelection print("Ok. You're balance is now at " + balanceAfterStrength + " skill points.") TypeError: cannot concatenate 'str' and 'int' objects
有人知道如何解決這個問題嗎?先行感謝。spa
2、答案code
你不能將整型(int)與字符串(string)連在一塊兒。你須要使用'str'函數將整型(int)轉換爲字符型(string),或者使用'formatting'格式化輸出。orm
將
print("Ok. Your balance is now at " + balanceAfterStrength + " skill points.")
改成:
({} .format方式)
print("Ok. Your balance is now at {} skill points.".format(balanceAfterStrength))
或改成:
(使用str函數轉換類型)
print("Ok. Your balance is now at " + str(balanceAfterStrength) + " skill points.")
或按照下面的一條評論所說起的那樣作,使用','將不一樣的字符串傳遞給print函數,而不是使用'+'鏈接。(涉及的評論爲:你不能使用','鏈接字符串;你能夠用','將參數分開傳遞給print函數,這些參數會以空格分割,一個接一個的打印出來,)
print("Ok. Your balance is now at ", balanceAfterStrength, " skill points.")
3、總結
當同時打印字符及整型變量時,有如下幾種方式來避免「TypeError」報錯。
假設變量temp = 3,要輸出的內容爲the number you input is 3.
1.使用str強制將整型轉換爲字符型
print 'the nume you input is ' + str(temp)
2.使用格式化輸出(python2中適用,「format % values」形式),詳細使用方法可參考官方文檔:https://docs.python.org/2/library/stdtypes.html#string-formatting
print 'the nume you input is %s' % temp
3.使用" str.format()
"(python2.6以上)格式化輸出,詳細使用方法可參考官方文檔:https://docs.python.org/3/library/string.html#string-formatting
print 'the nume you input is {}' .format(temp)
4.使用逗號將變量和字符串分隔
print 'the nume you input is' , temp
4、% 及 .format() 兩種格式化輸出對比
更多實例對比請參考:
https://github.com/ulope/pyformat.info
基本輸出 Old '%s %s' % ('one', 'two') New '{} {}'.format('one', 'two') Output one two Old '%d %d' % (1, 2) New '{} {}'.format(1, 2) Output 1 2 #右對齊 Old '%10s' % ('test',) New '{:>10}'.format('test') Output test #test左邊有六個空格 #左對齊 Old '%-10s' % ('test',) New '{:10}'.format('test') Output test #test右邊有六個空格 #字典 person = {'first': 'Jean-Luc', 'last': 'Picard'} New '{p[first]} {p[last]}'.format(p=person) Output Jean-Luc Picard #列表 data = [4, 8, 15, 16, 23, 42] New '{d[4]} {d[5]}'.format(d=data) Output 23 42 #Accessing arguments by position: >>> '{0}, {1}, {2}'.format('a', 'b', 'c') 'a, b, c' >>> '{}, {}, {}'.format('a', 'b', 'c') # 3.1+ only 'a, b, c' >>> '{2}, {1}, {0}'.format('a', 'b', 'c') 'c, b, a' >>> '{2}, {1}, {0}'.format(*'abc') # unpacking argument sequence 'c, b, a' >>> '{0}{1}{0}'.format('abra', 'cad') # arguments' indices can be repeated 'abracadabra' #Accessing arguments by name: >>> 'Coordinates: {latitude}, {longitude}'.format(latitude='37.24N', longitude='-115.81W') 'Coordinates: 37.24N, -115.81W' >>> coord = {'latitude': '37.24N', 'longitude': '-115.81W'} >>> 'Coordinates: {latitude}, {longitude}'.format(**coord) 'Coordinates: 37.24N, -115.81W'