如何在Python中连接字符串和数字?

时间:2011-08-08 11:35:27

标签: python

我试图在Python中连接字符串和数字。当我尝试这个时,它给了我一个错误:

"abc" + 9

错误是:

Traceback (most recent call last):
  File "<pyshell#5>", line 1, in <module>
    "abc" + 9
TypeError: cannot concatenate 'str' and 'int' objects

为什么我无法做到这一点?

如何我如何在Python中连接字符串和数字?

7 个答案:

答案 0 :(得分:77)

Python是strongly typed。没有隐式类型转换。

您必须执行以下操作之一:

"asd%d" % 9
"asd" + str(9)

答案 1 :(得分:27)

如果它按预期的方式工作(产生"abc9"),那么"9" + 9会提供什么? 18"99"

要消除这种歧义,您需要在这种情况下明确要转换的内容:

"abc" + str(9)

答案 2 :(得分:12)

由于Python is a strongly typed语言,在Perl中连接字符串和整数是没有意义的,因为没有定义的方法来相互“添加”字符串和数字。

  

明确比隐含更好。

...说"The Zen of Python",所以你必须连接两个字符串对象。您可以使用内置的str()函数从整数创建一个字符串来完成此操作:

>>> "abc" + str(9)
'abc9'

或者使用Python's string formatting operations

>>> 'abc%d' % 9
'abc9'

或许更好,使用str.format()

>>> 'abc{0}'.format(9)
'abc9'

禅也说:

  

应该有一个 - 最好只有一个 - 显而易见的方法。

这就是我给出三个选项的原因。它继续说......

  

虽然这种方式起初可能并不明显,除非你是荷兰人。

答案 3 :(得分:6)

这样的事情:

"abc" + str(9)

"abs{0}".format(9)

"abs%d" % (9,)

答案 4 :(得分:2)

您必须将int转换为字符串:

"abc" + str(9)

答案 5 :(得分:1)

这样做:

"abc%s" % 9
#or
"abc" + str(9)

答案 6 :(得分:0)

您必须将int转换为字符串。

# This program calculates a workers gross pay

hours = float(raw_input("Enter hours worked: \n"))

rate = float(raw_input("Enter your hourly rate of pay: \n"))

gross = hours * rate

print "Your gross pay for working " +str(hours)+ " at a rate of " + str(rate) + " hourly is $"  + str(gross)