Beginner Question | len() function

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

Please can you help me how to achieve this?

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”)

This is not a problem for me anymore!

1 Like

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.

Cheers,
Cameron Simpson cs@cskk.id.au

1 Like

Thank you so much, Cameron for this valuable advice. I am enjoying my learning curve with Python.

Or, if you DO want the string:

name = input("Write your name: ")
message = f"The length of your name, {name} is: {len(name)} characters")
print(message)

f-strings are really handy!

There are lots of introductions to them – here is just one:

1 Like