TypeError: Can only concatenate str (not “int”) to str (simple Python programme)

后端 未结 11 626
逝去的感伤
逝去的感伤 2020-12-07 05:17

I wrote this simple code and tried to execute in Windows 10 CMD ... and it gets the error message :

TypeError: Can only concatenate str (not \"int\") to str
         


        
相关标签:
11条回答
  • 2020-12-07 06:09

    Python is strongly typed, so it does not do type coercion unless you tell it to.

    You get that error if you try to add a number to a string, because based on the first operand it figures you want to concatenate strings.

    If you try to add a string to a number, you get “unsupported operand types” instead, but it’s the same problem.

    If you want to turn a number-in-a-string into an int you can add, use int(). If you want to turn a number value into a string you can concatenate, use str().

    0 讨论(0)
  • 2020-12-07 06:11

    Convert age to int to do your maths:

    finalAge = int(age) + factor
    

    And as a bonus you could use the .format() option:

    print("In {0} years you will be {1} years old, {2}!".format(factor, finalAge, userName))
    
    0 讨论(0)
  • 2020-12-07 06:11

    I think this type of error: TypeError: can only concatenate str (not "float") to str

    The reason was Python use comma (,) to stick all element in print() function together. little different from Java that they used plus (+) sign to stick and output the result.

    Note: double check all print() function to see did you put + sign and it should be replace by ,

    0 讨论(0)
  • 2020-12-07 06:21

    The input() command in line 2 of your code would turn any input provided by the user into a STRING. Therefore, when you try to add that STRING to a number (float or integer; in your case you have an integer i.e. factor=2) it won't (and shouldn't!) work.

    Therefore, for the + operation to continue, both the quantities to the left and right of that + sign must be of the same type (strings, or numbers)

    0 讨论(0)
  • 2020-12-07 06:21

    I had the same problem with django and I solved it by clearing the chrome cache

    0 讨论(0)
提交回复
热议问题