Python 如何连接 str 和 int 对象?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25675943/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 23:29:05  来源:igfitidea点击:

How can I concatenate str and int objects?

pythonstringpython-3.xconcatenationpython-2.x

提问by Zero Piraeus

If I try to do the following:

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

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

I get the following error in Python 3.x:

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

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

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

...以及 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?

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

采纳答案by Zero Piraeus

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

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

>>> 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 another1in order to make operations "make sense", because that would be confusing: for instance, you might think that '3' + 5should mean '35', but someone else might think it should mean 8or even '8'.

通常,Python 不会为了使操作“有意义”而将对象从一种类型隐式转换为另一种类型1,因为这会令人困惑:例如,您可能认为这'3' + 5应该意味着'35',但其他人可能认为它应该意思是8甚至'8'

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

同样,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

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:

但是,还有更好的方法。根据您使用的 Python 版本,有 3 种不同的字符串格式可用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.'

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

是否使用% 插值str.format()f 字符串取决于您: % 插值已经存在时间最长(并且对具有 C 背景的人来说是熟悉的),str.format()通常更强大,并且 f 字符串仍然更强大(但仅在 Python 3.6 及更高版本中可用)。

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

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

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

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



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

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

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

2Actually four ... but template stringsare rarely used and somewhat awkward.

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

回答by John Moutafis

TL;DR

TL; 博士

  1. either: print("You have " + str(things) + " things.")(the old school way)

  2. or: print("You have {} things.".format(things))(the new pythonic and recommended way)

  1. 要么:(print("You have " + str(things) + " things.")老派方式)

  2. 或:(print("You have {} things.".format(things))新的pythonic和推荐方式)



A bit more verbal explanation:
Although there is anything not covered from the excellent @Zero Piraeus answer above, I will try to "minify" it a bit:
You cannot concatenate a string and a number (of any kind) in python because those objects have different definitions of the plus(+) operator which are not compatible with each other (In the str case + is used for concatenation, in the number case it is used to add two numbers together). So in order to solve this "misunderstanding" between objects:

多一点口头解释:
尽管上面出色的@Zero Piraeus 答案中没有涵盖任何内容,但我会尝试将其“缩小”一点
您无法在 python 中连接字符串和数字(​​任何类型),因为这些对象对 plus(+) 运算符有不同的定义,它们彼此不兼容(在 str 情况下 + 用于连接,在 number 情况下它用于将两个数字相加)。所以为了解决这个对象之间的“误会”:

  1. The old school way is to cast the number to string with the str(anything)method and then concatenate the result with another string.
  2. The more pythonic and recommended way is to use the formatmethod which is very versatile (you don't have to take my word on it, read the documentation and thisarticle)
  1. 老派的方法是使用该str(anything)方法将数字转换为字符串, 然后将结果与另一个字符串连接起来。
  2. 更pythonic和推荐的方法是使用非常通用的格式方法(你不必相信我的话,阅读文档和这篇文章)

Have fun and doread the @Zero Piraeus answer it surely worth your time!

玩得开心,一定要阅读@Zero Piraeus 的回答,这绝对值得你花时间!

回答by ngub05

Python 2.x

蟒蛇 2.x

  1. 'You have %d things.' % things[1]
  2. 'You have {} things.'.format(things)[2]
  1. 'You have %d things.' % things[ 1]
  2. 'You have {} things.'.format(things)[ 2]

Python 3.6+

蟒蛇 3.6+

  1. 'You have %d things.' % things[1]
  2. 'You have {} things.'.format(things)[2]
  3. f'You have {things} things.'[3]
  1. 'You have %d things.' % things[ 1]
  2. 'You have {} things.'.format(things)[ 2]
  3. f'You have {things} things.'[ 3]


Reference

参考

  1. printf-style String Formatting
  2. Built-in types -> str.format
  3. Formatted string literals
  1. printf 风格的字符串格式
  2. 内置类型 -> str.format
  3. 格式化字符串文字

回答by Rohit Singh

str.format()

str.format()

Another alternative is using str.format()method to concatenate an int into a String.

另一种选择是使用str.format()方法将一个 int 连接成一个字符串。

In your case:

在你的情况下:

Replace

代替

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

With

print("You have {} things".format(things))

Bonus: for multiple concatenation

奖励:用于多重连接

if you have

如果你有

first = 'rohit'
last = 'singh'
age = '5'
print("My Username is {}{}{}".format(first,age,last))