54

I was trying to concatenate a string and a number in Python. It gave me an error when I tried this:

"abc" + 9

The error is:

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

Why am I not able to do this?

How can I concatenate a string and a number in Python?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
NOOB
  • 2,717
  • 4
  • 22
  • 22

7 Answers7

95

Python is strongly typed. There are no implicit type conversions.

You have to do one of these:

"asd%d" % 9
"asd" + str(9)
Jochen Ritzel
  • 104,512
  • 31
  • 200
  • 194
29

If it worked the way you expected it to (resulting in "abc9"), what would "9" + 9 deliver? 18 or "99"?

To remove this ambiguity, you are required to make explicit what you want to convert in this case:

"abc" + str(9)
vstrien
  • 2,547
  • 3
  • 27
  • 47
14

Since Python is a strongly typed language, concatenating a string and an integer, as you may do in Perl, makes no sense, because there's no defined way to "add" strings and numbers to each other.

Explicit is better than implicit.

...says "The Zen of Python", so you have to concatenate two string objects. You can do this by creating a string from the integer using the built-in str() function:

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

Alternatively, use Python's string formatting operations:

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

Perhaps better still, use str.format():

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

The Zen also says:

There should be one-- and preferably only one --obvious way to do it.

Which is why I've given three options.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
johnsyweb
  • 136,902
  • 23
  • 188
  • 247
8

Either something like this:

"abc" + str(9)

or

"abs{0}".format(9)

or

"abs%d" % (9,)
xubuntix
  • 2,333
  • 18
  • 19
  • 1
    +1 for suggesting `format`. There's no point in the parenthesis in `"abs%d" % (9)` as it's equivalent to `"abs%d" % 9`. More correct and extendable would be to make it a tuple with one element: `"abs%d" % (9,)`, but best of all would be to use `format` instead. :) – Lauritz V. Thaulow Aug 08 '11 at 11:53
  • @lazyr: you are right, I wanted to write (9,). Changed. – xubuntix Aug 08 '11 at 12:06
2

You have to convert the int into a string:

"abc" + str(9)
senderle
  • 145,869
  • 36
  • 209
  • 233
1

You would have to convert the int into a string.

# 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)
Paul Roub
  • 36,322
  • 27
  • 84
  • 93
0

Do it like this:

"abc%s" % 9
#or
"abc" + str(9)
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
guettli
  • 25,042
  • 81
  • 346
  • 663