String Concatenate Typeerror: Can Only Concatenate Str (Not "Int") to Str"

TypeError: can only concatenate str (not int ) to str but when trying to change var's to str, I get a different error

I already fixed the problem. The problem being I needed to change
Time
and
Pieces
To
float(time)
and
float(pieces) and it works.

can only concatenate str (not 'int') to str

The + operator can work in multiple contexts. In this case, the relevant use cases are:

  • When concatenating stuff (strings, for example);

  • When you want to add numbers (int, float and so on).

So when you use the + in a concept that uses both strings and int variables (x, y and z), Python won't handle your intention correctly. In your case, in which you want to concatenate numbers in the sentence as if they were words, you'd have to convert your numbers from int format to string format. Here, see below:

def addition():
x = int(input("Please enter the first number:"))
y = int(input("Please enter the second number:"))
z = x+y
print("The sum of " + str(x) + " and " + str(y) + " gives " + str(z))

Python: TypeError: can only concatenate str (not int ) to str : variable stored wrong

You can concate only strings, so before concate all your userinputs you must "convert" them into strings

Example1:

command1 = "RAMP " + " ".join(map(str, [userinput5, userinput1, userinput2, userinput4, userinput3]))

Example2:

command1 = f"RAMP {userinput5} {userinput1} {userinput2} {userinput4} {userinput3}"

ERROR: can only concatenate str (not int ) to str

Quite the opposite, you should have added int(...) around it.

It tries to add 1 to item and it really can't be string then.

Edit: it wasn't this, but instead incorrect usage of the library. Forgot .first() after query to actually retrieve the result.

TypeError: can only concatenate str (not NoneType ) to str in voting bot

The error is descriptive: one of the parts you are atempting to concatenate in your log message is a None object, and the "+" operator is not defined for it.

However, concatenating strings with "+" in Python is usually just done by people learning Python coming from other languages. Other ways of interpolating data in strings are far easier to type and read.

From Python 3.6+ the recomended way is interpolating with "f"strings: strings with an f-prefix to the opening quote, can resolve Python expressions placed inside brackets inside it.

So, just replace your erroring line for:

 print(f"[!] { ex.strerror }: { ex.filename}")

Unlike the + operator, string interpolation via f-strings, the %operator or via the .format method will automatically cast its operands to string, and None will not error.



Related Topics



Leave a reply



Submit