這裏的問題是,+
操作員(至少)在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).'
無論您使用% interpolation,str.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很少使用,有點尷尬。
請注意,這是打算作爲一個典型答案的一個共同的問題...請除非你確定對方不要靠近重複問題有更好,更完整的答案。 – 2014-09-04 22:29:14