如何连接str和int对象? [英] How can I concatenate str and int objects?

查看:102
本文介绍了如何连接str和int对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

If I try to do the following:

things = 5
print("You have " + things + " things.")

我在Python 3.x中遇到以下错误:

I get the following error in Python 3.x:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: must be str, not int

...以及Python中的类似错误2.x:

... and a similar error in Python 2.x:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: cannot concatenate 'str' and 'int' objects

我该如何解决

推荐答案

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

The problem here is that the + operator has (at least) two different meanings in Python: for numeric types, it means "add the numbers together":

>>> 1 + 2
3
>>> 3.4 + 5.6
9.0

...对于序列类型,其含义是连接序列:

... and for sequence types, it means "concatenate the sequences":

>>> [1, 2, 3] + [4, 5, 6]
[1, 2, 3, 4, 5, 6]
>>> 'abc' + 'def'
'abcdef'

通常,Python不会 t隐式地将对象从一种类型转换为另一种 1 ,以使操作有意义,因为这会造成混淆:例如,您可能会认为'3'+ 5 应该表示 '35',但是其他人可能会认为它应该表示 8 或甚至'8'

As a rule, Python doesn't implicitly convert objects from one type to another1 in order to make operations "make sense", because that would be confusing: for instance, you might think that '3' + 5 should mean '35', but someone else might think it should mean 8 or even '8'.

类似地,Python不允许您连接两种不同类型的序列:

Similarly, Python won't let you concatenate two different types of sequence:

>>> [7, 8, 9] + 'ghi'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: can only concatenate list (not "str") to list

因此,无论您要连接还是添加,都需要显式进行转换。

Because of this, you need to do the conversion explicitly, whether what you want is concatenation or addition:

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

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

However, there is a better way. Depending on which version of Python you use, there are three different kinds of string formatting available2, which not only allow you to avoid multiple + operations:

>>> 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.'

...但还可以控制值的显示方式:

... but also allow you to control how values are displayed:

>>> 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字符串由您决定:%内插法最长(并且对于C语言背景的人来说是很熟悉的), str.format()通常更强大,而f字符串仍然更强大(但仅在Python 3.6和更高版本中可用)。

Whether you use % interpolation, str.format(), or f-strings is up to you: % interpolation has been around the longest (and is familiar to people with a background in C), str.format() is often more powerful, and f-strings are more powerful still (but available only in Python 3.6 and later).

另一种选择是利用事实如果您给 print 多个位置参数,它将使用 sep 关键字参数将字符串表示形式连接在一起(默认到' ’):

Another alternative is to use the fact that if you give print multiple positional arguments, it will join their string representations together using the sep keyword argument (which defaults to ' '):

>>> things = 5
>>> print('you have', things, 'things.')
you have 5 things.
>>> print('you have', things, 'things.', sep=' ... ')
you have ... 5 ... things.

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

... but that's usually not as flexible as using Python's built-in string formatting abilities.

1 尽管数字类型是一个例外,但大多数人会同意'要做的事情:

1 Although it makes an exception for numeric types, where most people would agree on the 'right' thing to do:

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

2 实际上是四个...,但是模板字符串很少使用并且有点尴尬。

2 Actually four ... but template strings are rarely used and somewhat awkward.

这篇关于如何连接str和int对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆