ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

python – 如何连接str和int对象?

2019-09-11 04:57:48  阅读:176  来源: 互联网

标签:python python-3-x string 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

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

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

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

解决方法:

这里的问题是操作符在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版本,有三种不同的字符串格式可用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).'

你是否使用% interpolation,str.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很少使用,有点尴尬.

标签:python,python-3-x,string,concatenation,python-2-x
来源: https://codeday.me/bug/20190911/1803719.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有