TypeError: can only concatenate str (not "int") to str in Python

Dung Do Tien Aug 08 2021 60

Hello, I just start learning Python 3.8 and I have some values I need to concat them as below:

 fullName = "Joih Speaker"
age = 4
print("My name:" + fullName + " and age: " + age)

And I got an error TypeError: can only concatenate str (not "int") to str

 Traceback (most recent call last):
  File "main.py", line 3, in <module>
    print("My name:" + fullName + " and age: " + age)
TypeError: can only concatenate str (not "int") to str

Pls help me why and how can I solve it?

Have 2 answer(s) found.
  • T

    Trọng Hiếu Aug 08 2021

    You need to change the number to string data type:

     fullName = "Python 3.8"
    age = "4"
    print("My name:" + fullName + " and age: " + age)

    Or you can use str() method help convert numbers to strings.

     fullName = "Python 3.8"
    age = str(4)
    print("My name:" + fullName + " and age: " + age) 
  • R

    Ruslan Kurbanali Aug 08 2021

    We have many ways to convert integer to string in Python.

    1. Using str() function 

     num = 10
     
    # check  and print type of num variable
    print(type(num))
     
    # convert the num into string
    converted_num = str(num)
     
    # check  and print type converted_num variable
    print(type(converted_num))

    2. Using "%s" keyword

     num = 10
     
    # check  and print type of num variable
    print(type(num))
     
    # convert the num into string and print
    converted_num = "%s" % num
    print(type(converted_num))

    3. Using .format() function

     num = 10
     
    # check  and print type of num variable
    print(type(num))
     
    # convert the num into string and print
    converted_num = "{}".format(num)
    print(type(converted_num))

    4. Using f-string

     num = 10
     
    # check  and print type of num variable
    print(type(num))
     
    # convert the num into string
    converted_num = f'{num}'
     
    # print type of converted_num
    print(type(converted_num)) 
Leave An Answer
* NOTE: You need Login before leave an answer

* Type maximum 2000 characters.

* All comments have to wait approved before display.

* Please polite comment and respect questions and answers of others.

Popular Tips

X Close