問(wèn)題描述
在 Python 中,以下代碼會(huì)產(chǎn)生錯(cuò)誤:
In Python, the following code produces an error:
a = 'abc'
b = 1
print(a + b)
(錯(cuò)誤是TypeError: cannot concatenate 'str' and 'int' objects").
(The error is "TypeError: cannot concatenate 'str' and 'int' objects").
為什么 Python 解釋器在遇到這些類型的串聯(lián)時(shí)不會(huì)自動(dòng)嘗試使用 str() 函數(shù)?
Why does the Python interpreter not automatically try using the str() function when it encounters concatenation of these types?
推薦答案
問(wèn)題是轉(zhuǎn)換有歧義,因?yàn)?code>+表示字符串拼接和數(shù)字加法.以下問(wèn)題同樣有效:
The problem is that the conversion is ambiguous, because +
means both string concatenation and numeric addition. The following question would be equally valid:
為什么 Python 解釋器在遇到 addition 這些類型時(shí)不會(huì)自動(dòng)嘗試使用 int() 函數(shù)?
Why does the Python interpreter not automatically try using the int() function when it encounters addition of these types?
這正是不幸地困擾著 Javascript 的松散類型問(wèn)題.
This is exactly the loose-typing problem that unfortunately afflicts Javascript.
這篇關(guān)于為什么 Python 在連接字符串時(shí)不進(jìn)行類型轉(zhuǎn)換?的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!