如何连接字符串和整数?
如果我尝试做以下操作:
things = 5
print("You have " + things + " things.")
我在Python 3.x中会遇到以下错误:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can only concatenate str (not "int") to str
在Python 2.x中也会出现类似的错误:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: cannot concatenate 'str' and 'int' objects
我该如何解决这个问题呢?
1 个回答
142
这里的问题是,+
这个符号在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不会自动把一种类型的对象转换成另一种类型,以便让操作“看起来合理”,因为这样会让人困惑。例如,你可能会认为 '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).'
你可以选择使用 % 插值、str.format()
,或者 f-strings:% 插值是最早出现的(对于有C语言背景的人来说比较熟悉),str.format()
通常更强大,而f-strings更加强大(但仅在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 不过对于数字类型,它会有例外,大多数人会同意“正确”的做法:
>>> 1 + 2.3
3.3
>>> 4.5 + (5.6+7j)
(10.1+7j)
2 实际上有四种,但 模板字符串很少使用,而且有点尴尬。
其他资源: