2014-09-04 172 views
37

如果我試圖做到以下幾點:如何連接str和int對象?

things = 5 
print("You have " + things + " things.") 

我得到的Python 3.X以下錯誤:

Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
TypeError: must be str, not int 

...並在Python 2.x的一個類似的錯誤:

Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
TypeError: cannot concatenate 'str' and 'int' objects 

我該如何解決這個問題?

+7

請注意,這是打算作爲一個典型答案的一個共同的問題...請除非你確定對方不要靠近重複問題有更好,更完整的答案。 – 2014-09-04 22:29:14

回答

58

這裏的問題是,+操作員(至少)在Python兩種不同的含義:對於數值類型,它的意思是「加數字加在一起」:

>>> 1 + 2 
3 
>>> 3.4 + 5.6 
9.0 

...和序列類型,它的意思是「串聯序列」:

>>> [1, 2, 3] + [4, 5, 6] 
[1, 2, 3, 4, 5, 6] 
>>> 'abc' + 'def' 
'abcdef' 

作爲一項規則,Python不隱式地從一種類型轉換對象爲了使操作「意義」,因爲那將是令人困惑:因爲in立場,你可能會認爲'3' + 5應該意味着'35',但其他人可能會認爲它應該意味着8甚至'8'

同樣,Python將不會讓您連接兩個不同類型的序列:

>>> [7, 8, 9] + 'ghi' 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
TypeError: can only concatenate list (not "str") to list 

正因爲如此,你需要做的轉換明確,你想要的是串聯或增加:

>>> 'Total: ' + str(123) 
'Total: 123' 
>>> int('456') + 789 
1245 

但是,還有更好的辦法。根據您所使用的Python版本,有三種不同類型的字符串格式化可,這不僅可以讓你避免多個+操作:

>>> things = 5 

>>> 'You have %d things.' % things # % interpolation 
'You have 5 things.' 

>>> 'You have {} things.'.format(things) # str.format() 
'You have 5 things.' 

>>> f'You have {things} things.' # f-string (since Python 3.6) 
'You have 5 things.' 

...也讓你控制值顯示:

>>> value = 5 
>>> sq_root = value ** 0.5 
>>> sq_root 
2.23606797749979 

>>> 'The square root of %d is %.2f (roughly).' % (value, sq_root) 
'The square root of 5 is 2.24 (roughly).' 

>>> 'The square root of {v} is {sr:.2f} (roughly).'.format(v=value, sr=sq_root) 
'The square root of 5 is 2.24 (roughly).' 

>>> f'The square root of {value} is {sq_root:.2f} (roughly).' 
'The square root of 5 is 2.24 (roughly).' 

無論您使用% interpolationstr.format(),或f-strings取決於你:%插值已經是最長的了(對於C中的背景的人來說是熟悉的),str.format()通常更強大,而f-字符串仍然更強大(但只能在Python 3.6及更高版本中使用) 。

另一種方法是使用的事實,如果你給print多個位置參數,它會加入他們的字符串表示一起使用sep關鍵字參數(默認爲' '):

>>> things = 5 
>>> print('you have', things, 'things.') 
you have 5 things. 
>>> print('you have', things, 'things.', sep=' ... ') 
you have ... 5 ... things. 

...但這通常不如使用Python內置的字符串格式化功能那麼靈活。


雖然它使一個異常的數字類型,其中大部分人都對 '正確' 的事:

>>> 1 + 2.3 
3.3 
>>> 4.5 + (5.6+7j) 
(10.1+7j) 

實際上有四種...但template strings很少使用,有點尷尬。

+1

這個答案很好,它提供了背景信息和多種解決方案,但實際的解決方案被埋在了文本牆的中間。它將從一開始就受益於TLDR(作爲[漸進披露]形式(https://en.wikipedia.org/wiki/Progressive_disclosure))。 – Helen 2016-12-29 20:10:19

+2

@ Helen這個規範Q/A有意識地寫成誘餌和開關 - 這個問題有一個「gimme teh codez」風格,而答案提出了* not *立即提供了「gimme teh codez」解決方案。我不同意倒金字塔/漸進式披露方法對於初學者級別的教學是一個很好的方法;它提高了糟糕程序員的表觀生產力(他們確實會「榨取」剩下的「tl」),而犧牲那些稍後維護代碼的人。我寧願幫助潛在的優秀程序員,也不願意爲可靠的程序員提供幫助,並嘗試爲SO做出相應貢獻。 – 2016-12-29 21:22:14

+0

很好的回答。我今天學到了一些新東西。 – alpeshpandya 2017-04-05 19:21:47

-2

解決此問題的最簡單方法之一(這是一個問題,不是嗎?)是習慣將任何類型的對象連接到字符串使用逗號(',')作爲連接運算符。這適用於print(),如果不夠完美(爲了避免拼接點'print()'插入的空格),只需使用下面提供的'myprint()'函數。 另一個方便的工具將是「concatByComma()」函數,其中 返回一個適當的字符串。

只要運行下面的代碼,有樂趣:)

def myprint(*arg): 
    strToPrint = "" 
    for item in arg: 
     strToPrint += str(item) 
    print(strToPrint) 
def concatByComma(*arg): 
    strToPrint = "" 
    for item in arg: 
     strToPrint += str(item) 
    return strToPrint 
I = "I"; i=5 
print(I, " am " , i , " years old") 
print(('s','o', I),[' wrote','it:'],' ',{1:'hour'},'and',5," min.") 
myprint(('s','o', I),[' wrote','it:'],' ',{1:'hour'},'and',5," min.") 
+0

您可以使用print(...,sep ='')'和[str.join](https://docs.python.org/3/library/stdtypes.html#str.join )方法 – Copperfield 2017-03-31 15:42:50

-2

的Python 2.x的

  1. 'You have %d things.' % things [1]
  2. 'You have {} things.'.format(things) [2]

的Python 3.6+

  1. 'You have %d things.' % things [1]
  2. 'You have {} things.'.format(things) [2]
  3. f'You have {things} things.' [3]

參考

  1. printf-style String Formatting
  2. Built-in types -> str.format
  3. Formatted string literals
+0

這對現有答案沒有任何增加。 – 2017-04-02 20:30:29

+0

@ZeroPiraeus:沒有。曾聽說過「可讀性」? – ngub05 2017-04-07 13:13:47

+0

僅僅因爲有人在我面前回答了一個問題,這並不意味着我可以用我自己的方式來接近它(我認爲最能描述答案的方式)。如果你認爲這是錯誤的,我認爲這並不比錯誤地回答某人的回答更爲錯誤,因爲你也對同一個問題有了答案。 – ngub05 2017-04-07 13:16:37

-3

爲什麼就不能?

things = 5 
print("You have " + str(things) + " things.") 

這對蟒蛇2 &蟒蛇都工作3

+0

這個答案並沒有增加新的東西。 – 2017-04-05 15:46:44

+0

你說得對,對不起 – 2017-04-07 14:34:21

相關問題