Search code examples
python-3.xstringcastinginteger

Got this problem with simple lines, what does all of this mean?


variable3 = "four"
print(int(variable3) + 6)
ValueError: invalid literal for int() with base 10: 'four'

i wanted to try to cast the string that the variable3 has ("four"), converting it in an int, and then to add 6: obtaining the result "four6"... maybe


Solution

  • No need to make it an int, it will only concatenate as that by making 6 a str instead!

    >>> variable3 = "four"
    >>> print(variable3 + str(6))
    four6
    

    Note there are other, potentially more convenient ways to do this

    >>> print(variable3 + "6")     # just start with a string "6"
    four6
    >>> print(f"{variable3}{6}")   # string formatting
    four6
    

    Internally, + is interpreted as a call to use the __add__() method on the left side, which has internal logic to combine strings