is there a way to use numbers in a python array with strings

Question:

I get this error from python when I try to run my program does anyone know how to fix it.

ops.append(i+".)"+names[i]+"'s Living Quartersn")

TypeError: unsupported operand type(s) for +: 'int' and 'str'

ops is a array for choices.

names is a array with names to be made in to the ops array with a number for printing.

i is a increasing number for the choice number.

sorry if there have been other questions like this, I couldn’t find a solution

Asked By: ReTr0

||

Answers:

You’ll need to convert your integer to a string before you can concatenate it. You can do this with str(i).

Or you can accomplish your append line with f-strings, like so:

ops.append(f"{i}.) {names[i]}'s Living Quartersn")
Answered By: omermikhailk

You can use an integer in a string by either converting the integer to a string using
str(variable), or by formatting it in the string using F-strings.

String formatting example:

stringName = f"Number: {integer_variable}"

Which can also be used for other variable types and is a bit more readable than concatenating a ton of variables to strings using +

Answered By: Pepe Salad

There’s lots of fun ways to format strings in Python. I tend to prefer string.format just because of the flexibility.

ops = "{}{}.) {}'s Living Quartersn".format(ops, i, names[i])

Ideally, you’d include the formatting for ops in there as well, but since I didn’t have the code you used to generate it , I just showed you the closest I could.

Answered By: Donnie
ops.append(str(i)+".)"+str(names[i])+"'s Living Quartersn")

Should work!
str(VARIABLE) converts the VARIABLE into STR(String)

Answered By: Khetan K
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.