views:

165

answers:

5

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
+6  A: 
name = 'b' + str(num)

or

name = 'b%s' % num

as S.Lott notes, the mingle operator '%' is deprecated for Python 3 and up. And I stole the name "mingle" from INTERCAL but that's how I talk about it and wanted to see it in print at least once before - like the dodo - it vanishes from the face of the earth.

msw
The % is deprecated in Python 3. Might want to remove that one.
S.Lott
@S.Lott I have to work on some systems using python <2.6, namely Ubuntu 8.04. I didn't realize .format wasn't available, and after developing the code on Python 2.6, having to go and change all the .format commands to % was a bit of a pain. So, actually, while I prefer .format, if you need compatibility with every version, % is still your best bet - it IS present in Python 3, while .format is not present in python 2.5 and below.
Alex JL
+2  A: 

Yeah, python doesn't having implicit int to string conversions.

try str(num) instead

Alan
+3  A: 

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

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

or the new .format string method

name="b{0}".format(num)
Alex JL
The % is deprecated in Python 3. Might want to remove that one.
S.Lott
I can't edit it now it seems, so noted here that % is deprecated. Also worth mentioning is that .format isn't available before Python 2.6.
Alex JL
+1  A: 
name = "b{0:d}".format( num )
S.Lott
+1  A: 

Correct answers have already been given but I want to chime in and say that you should always use str(var) every time you intend to use var as a string, regardless of whether you know it is a string or not.

Better safe than sorry.

whaley
But, what's the worst that can happen? A TypeError?
Waterfox