1

Whenever I run my code an error comes which states "TypeError: can only concatenate str (not "int") to str" this comes in the output = output + text.yellow + number line. I understand thati can't add an integer with a string and for that I have also changed its type just before the line but it doesn't seem to work and I cant understand what the error is and how to solve it, hep would be really appreciated

My code is as below:

Info: The text.yellow is a class attribute which just changes the text to yellow color. available_numbers and choosen_numbers is a list

def print_board():
number = 1
output = ""

while number < 91:
    if number in available_numbers:
        str(number)
        output = output + text.yellow + number
        int(number)
    elif number in choosen_numbers:
        str(number)
        output = output + text.green + number
        int(number)
    number += 1

print(output)
  • Does this answer your question? [Turn a variable from string to integer in python](https://stackoverflow.com/questions/50518635/turn-a-variable-from-string-to-integer-in-python) – Iguananaut Jun 17 '22 at 10:12
  • Type will not change by reference, you need to assign back to the variable once you change the type. – Noman Ghani Jun 17 '22 at 10:20

5 Answers5

0

You should store str(number) and int(number) into the number variable if you want to actually change number. But anyway, you should use f-string or format in order to concat int and strings, for example:

output = f"{output} {text.yellow} {number}"

just in case you still want to format it using +, you should do something like:

output = output + text.yellow + str(number)

make sure that text.yellow is also a str

omer.hazan
  • 129
  • 2
0

The variable number is still an integer. Try this instead: output = output + text.green + str(number) or store the string version in a variable like this string_number = str(number) and use that variable for concatenation

Vasile Coman
  • 191
  • 1
  • 8
0

Precisely you can convert integer to string but unfortunately, you cannot save it anywhere. Do this

   number=str(number)

or

this

output = output + text.yellow + str(number)

instead of this

str(number)
Mehmaam
  • 573
  • 7
  • 22
0

Try this:

def print_board():
number = 1
output = ""

while number < 91:
    if number in available_numbers:
        output = output + text.yellow + str(number) 
    elif number in choosen_numbers:
        output = output + text.green + str(number)
    number += 1

print(output)
Konstantinos
  • 109
  • 1
  • 6
0

You don't need to change the type every time when you need to change it. You can change the type at the moment when you need it and don't have to change it back))