Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making a string out of a string and an integer in Python [duplicate]

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 
like image 657
Kudu Avatar asked May 12 '10 22:05

Kudu


People also ask

How do you multiply a string and a number in Python?

When you multiply a string by an integer, Python returns a new string. This new string is the original string, repeated X number of times (where X is the value of the integer). In the following example, we're going to multiply the string 'hello' by a few integers. Take note of the results.

Can we concatenate string and integer in Python?

Python supports string concatenation using + operator. In most of the programming languages, if we concatenate a string with an integer or any other primitive data types, the language takes care of converting them to string and then concatenate it.

How do I print a string and int concatenate in Python?

If you want to concatenate a string and a number, such as an integer int or a floating point float , convert the number to a string with str() and then use the + operator or += operator.

How do you duplicate a string in Python?

To make a copy of a string, we can use the built-in slice syntax [:] in Python. Similarly, we can also do it by assigning a string to the new variable. or we can use the str() function to create a string copy.


1 Answers

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.

like image 62
msw Avatar answered Sep 19 '22 03:09

msw