Please can someone tell me what mistake I am doing here?
length = input("Write your name: ")
print("Length of your name is: " + len(length))
When I run the above code I get the below error:
Write your name: hkhkk
Traceback (most recent call last):
File “main.py”, line 2, in
print("Length of your name is: " + len(length))
TypeError: can only concatenate str (not “int”) to str
I have found the solution. My mistake was that I was trying to concatenate a string with an integer. I have just now learnt that the way to get this done is by converting the integer to a string. So my code should be as below:
length = len(input("Write your name: "))
new_length=str(length)
print(“Length of your name is: " + new_length + " characters”)
By Somnath Chattaraj via Discussions on Python.org at 07Aug2022 06:47:
I have found the solution. My mistake was that I was trying to concatenate a string with an integer. I have just now learnt that the way to get this done is by converting the integer to a string. So my code should be as below:
length = len(input("Write your name: "))
new_length=str(length)
print(“Length of your name is: " + new_length + " characters”)
A better way to writ this is:
length = len(input("Write your name: "))
print("Length of your name is:", length, "characters")
because print() prints all its arguments, converted to str,
separated by a space. You do not need to hand assemble a single string
on your own.