Python 如何连接str和int对象?

Python 如何连接str和int对象?,python,string,python-3.x,concatenation,python-2.x,Python,String,Python 3.x,Concatenation,Python 2.x,如果我尝试执行以下操作: 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 回溯(最近一次呼叫最后一次): 文件“”,第1行,在 TypeError:必须是str,而

如果我尝试执行以下操作:

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
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
TypeError:必须是str,而不是int
。。。Python 2.x中还有一个类似的错误:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: cannot concatenate 'str' and 'int' objects
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
TypeError:无法连接'str'和'int'对象

如何解决这个问题?

这里的问题是
+
运算符在Python中(至少)有两种不同的含义:对于数字类型,它意味着“将数字相加”:

。。。对于序列类型,它意味着“连接序列”:

通常,Python不会隐式地将对象从一种类型转换为另一种类型1,以使操作“有意义”,因为这会令人困惑:例如,您可能认为
'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
但是,有更好的方法。根据您使用的Python版本的不同,有三种不同的字符串格式可用2,这不仅允许您避免多次
+
操作:

>>> things = 5
。。。但也允许您控制值的显示方式:

>>> value = 5
>>> sq_root = value ** 0.5
>>> sq_root
2.23606797749979
无论您是使用还是由您决定:%interpolation是最长的(对C语言背景的人来说也是很熟悉的),
str.format()
通常更强大,而f字符串更强大(但仅在Python 3.6及更高版本中可用)

另一种选择是使用这样一个事实,即如果您提供多个位置参数,它将使用
sep
关键字参数(默认为
'
)将它们的字符串表示连接在一起:

。。。但这通常不如使用Python内置的字符串格式化功能灵活


1尽管它对数字类型是一个例外,大多数人都会同意做“正确”的事情:

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

2实际上有四个,但很少使用,而且有点尴尬。

FYI:这个问题有9个答案被删除为重复答案。不要发布包含已接受答案内容的答案。将根据删除它们。
>>> 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).'
>>> things = 5
>>> print('you have', things, 'things.')
you have 5 things.
>>> print('you have', things, 'things.', sep=' ... ')
you have ... 5 ... things.
>>> 1 + 2.3
3.3
>>> 4.5 + (5.6+7j)
(10.1+7j)