这里的问题是,+
操作员(至少)在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