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

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

问题描述

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

东西 = 5打印(你有"+东西+东西.")

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

回溯(最近一次调用最后一次):文件<stdin>",第 1 行,在 <module> 中.类型错误:只能将 str(不是int")连接到 str

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

回溯(最近一次调用最后一次):文件<stdin>",第 1 行,在 <module> 中.类型错误:无法连接str"和int"对象

我怎样才能解决这个问题?

解决方案

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

<预><代码>>>>1 + 23>>>3.4 + 5.69.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'回溯(最近一次调用最后一次):文件<stdin>",第 1 行,在 <module> 中.类型错误:只能将列表(不是str")连接到列表

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

<预><代码>>>>'总计:' + str(123)'总计:123'>>>整数('456')+ 7891245

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

<预><代码>>>>东西 = 5

<预><代码>>>>你有 %d 件事."% 事物 # % 插值你有五件事."

<预><代码>>>>'你有 {} 个东西.'.format(things) # str.format()你有五件事."

<预><代码>>>>f'你有{东西}东西.# f-string (Python 3.6 起)你有五件事."

...但也允许您控制值的显示方式:

<预><代码>>>>值 = 5>>>sq_root = 值 ** 0.5>>>sq_root2.23606797749979

<预><代码>>>>'%d 的平方根是 %.2f(大致).%(值,sq_root)5 的平方根是 2.24(大约)."

<预><代码>>>>'{v} 的平方根是 {sr:.2f}(大致).'.format(v=value, sr=sq_root)5 的平方根是 2.24(大约)."

<预><代码>>>>f'{value} 的平方根是 {sq_root:.2f}(大致).5 的平方根是 2.24(大约)."

是否使用%插值, str.format()f-strings 由您决定:%插值的使用时间最长(对于有 C 背景的人来说很熟悉),str.format() 通常更强大,而 f-strings 仍然更强大(但仅在 Python 中可用3.6 及更高版本).

另一种选择是使用这样一个事实,如果您给 print 多个位置参数,它将使用 sep 关键字参数(默认为 <代码>' '):

<预><代码>>>>东西 = 5>>>打印('你有',东西,'东西.')你有5件事.>>>打印('你有',东西,'东西.',sep ='......')你有... 5 ... 东西.

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


1 虽然它对数字类型是个例外,但大多数人都会同意做正确"的事情:

<预><代码>>>>1 + 2.33.3>>>4.5 + (5.6+7j)(10.1+7j)

2 其实是四个,但是模板字符串很少使用,有点尴尬.


其他资源:

If I try to do the following:

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

I get the following error in Python 3.x:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: can only concatenate str (not "int") to str

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

How can I get around this problem?

解决方案

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'

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

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

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

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

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.

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


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 Actually four, but template strings are rarely used, and are somewhat awkward.


Other Resources:

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

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