Question

Making a string out of a string and an integer in Python

I get this error when trying to take an integer and prepend "b" to it, converting it into a string:

  File "program.py", line 19, in getname
    name = "b" + num
TypeError: Can't convert 'int' object to str implicitly

That's related to this function:

num = random.randint(1,25)
name = "b" + num
 45  55228  45
1 Jan 1970

Solution

 45
name = 'b' + str(num)

or

name = 'b%s' % num

Note that the second approach is deprecated in 3.x.

2010-05-12

Solution

 11

Python won't automatically convert types in the way that languages such as JavaScript or PHP do.

You have to convert it to a string, or use a formatting method.

name="b"+str(num)

or printf style formatting (this has been deprecated in python3)

name="b%s" % (num,)

or the new .format string method

name="b{0}".format(num)
2010-05-12