Making a string out of a string and an integer in

2019-01-01 15:59发布

This question already has an answer here:

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条回答
骚的不知所云
2楼-- · 2019-01-01 16:38

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.

查看更多
浮光初槿花落
3楼-- · 2019-01-01 16:39
name = "b{0:d}".format( num )
查看更多
姐姐魅力值爆表
4楼-- · 2019-01-01 16:44

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)
查看更多
梦寄多情
5楼-- · 2019-01-01 16:47

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'
查看更多
荒废的爱情
6楼-- · 2019-01-01 16:50

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

try str(num) instead

查看更多
情到深处是孤独
7楼-- · 2019-01-01 16:54
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.

查看更多
登录 后发表回答