45

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
Peter O.
  • 32,158
  • 14
  • 82
  • 96
Kudu
  • 6,570
  • 8
  • 27
  • 27
  • [This SO answer](https://stackoverflow.com/a/6380529/2071807) addresses why Python doesn't just cast the RHS of `+` to a `str` like Javascript does. It was kind of surprising to me but that answer explains it well. – LondonRob Oct 11 '17 at 10:07

5 Answers5

45
name = 'b' + str(num)

or

name = 'b%s' % num

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

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
msw
  • 42,753
  • 9
  • 87
  • 112
  • The % is deprecated in Python 3. Might want to remove that one. – S.Lott May 12 '10 at 22:32
  • 3
    @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. – JAL May 12 '10 at 22:36
  • 4
    @S.Lott % is not deprecated in Python3. [PEP 3101](https://www.python.org/dev/peps/pep-3101/) clearly mentions that *The new system does not collide with any of the method names of the existing string formatting techniques, so both systems can co-exist until it comes time to deprecate the older system.* – Bhargav Rao Nov 05 '16 at 18:40
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)
lugiorgi
  • 473
  • 1
  • 4
  • 12
JAL
  • 21,295
  • 1
  • 48
  • 66
  • The % is deprecated in Python 3. Might want to remove that one. – S.Lott May 12 '10 at 22:31
  • 2
    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. – JAL May 13 '10 at 00:34
3

Python 3.6 has f-strings where you can directly put the variable names without the need to use format:

>>> num=12
>>> f"b{num}"
'b12'
Georgy
  • 12,464
  • 7
  • 65
  • 73
Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219
2

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

try str(num) instead

Alan
  • 45,915
  • 17
  • 113
  • 134
0
name = "b{0:d}".format( num )
S.Lott
  • 384,516
  • 81
  • 508
  • 779