修復 Python 無法連線 STR 和 Int 物件錯誤

Haider Ali 2022年5月17日
修復 Python 無法連線 STR 和 Int 物件錯誤

在 Python 中,我們不能將字串和整數連線在一起。它們具有不同的基礎和記憶體空間,因為它們是完全不同的資料結構。

我們將告訴你如何在 Python 中解決此錯誤。

修復 Python 中的 cannot concatenate 'str' and 'int' objects 錯誤

看看下面的程式碼。

#String variable
s1="Hello"

#integer variable
number=5
#Trying to concatenate string with integer
s2=s1+number

如果我們在上面的程式碼示例中連線一個字串和一個整數,它會給出這個確切的錯誤 cannot concatenate 'str' and 'int' objects。那麼,我們怎樣才能避免這個錯誤呢?看一看。

#String variable
s1="Hello"

#integer variable
number=5

#Converting integer to string 
number_str=str(number)

#Concatenate number to a string
s2=s1+number_str
print(s2)

我們可以先將整數轉換為字串,然後將這兩個字串連線起來。

這裡的想法是你只能連線兩個字串,而不是字串或任何其他資料型別。因此,如果需要連線不同結構的字串,必須先將其轉換為字串。

Author: Haider Ali
Haider Ali avatar Haider Ali avatar

Haider specializes in technical writing. He has a solid background in computer science that allows him to create engaging, original, and compelling technical tutorials. In his free time, he enjoys adding new skills to his repertoire and watching Netflix.

LinkedIn

相關文章 - Python String

相關文章 - Python Error