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
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With