【问题标题】:How can I concatenate str and int objects?如何连接 str 和 int 对象?
【发布时间】:2022-01-19 13:32:14
【问题描述】:

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

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

我该如何解决这个问题?

【问题讨论】:

  • 仅供参考:有 9 个答案作为此问题的重复项被删除。不要发布包含已接受答案内容的答案。根据Flag Duplicate Answers on the same Question,它们将被删除。
  • 仅供参考:现在有 11 个答案作为重复项被删除。 所有与 OP 中的问题有关的方法都包含在接受的答案中。如果您发布已涵盖的答案,它将作为重复项被删除。 SO 使用相同的解决方案保留多个答案没有额外的价值。相反,请为现有答案投票。

标签: python string python-3.x concatenation python-2.x


【解决方案1】:

这里的问题是+ 运算符在 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 不会为了使操作“有意义”而隐式地将对象从一种类型转换为另一种类型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

因此,您需要明确地进行转换,无论您想要的是连接还是加法:

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

但是,还有更好的方法。根据您使用的 Python 版本,可以使用三种不同的字符串格式2,这不仅可以让您避免多次+ 操作:

>>> 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 虽然它对数字类型做了一个例外,但大多数人都会同意“正确”的做法:

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

2其实是四个,不过template strings很少用,有点别扭。


其他资源:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-10-23
    • 1970-01-01
    • 2014-08-19
    • 1970-01-01
    • 2012-08-04
    相关资源
    最近更新 更多