4

Here is the simple code but I can't run! My code is:

name = input("What is your name? ")
print("My name is "+name+". "+"My name length is " + len(str(name)))

and Output is:

What is your name? Ali
Traceback (most recent call last):
 File "c:\Users\iamAl\Desktop\Python\main.py", line 2, in <module> 
 print("My name is "+name+". "+"My name length is " + len(str(name)))
TypeError: can only concatenate str (not "int") to str
asked Feb 11, 2021 at 14:25
1
  • 1
    len() will always return an integer Commented Feb 11, 2021 at 14:26

4 Answers 4

3

Python is dynamic, but strongly typed. It won't let you add a string to an integer directly. You need to convert the types so they're compatible (meaning there has to be an addition operator that can handle adding them).

Possible solutions are:

  1. Cast one type to the other: str(len(name))
  2. Use a string interpolation method such as fstrings: f"My name is {name}. My name length is {len(name)}"
answered Feb 11, 2021 at 14:28
Sign up to request clarification or add additional context in comments.

Comments

3

You need to cast the int returned from len to an str, not cast str to str and then use len

print("My name is " + name + ". " + "My name length is " + str(len(name)))
answered Feb 11, 2021 at 14:27

Comments

2

As the other answers have pointed out, len returns an int, and you can't concatenate a str and an int with +.

However, you shouldn't be using + like this, as each + has to make a copy of its arguments. Use one of the string-formatting options instead, all of which will attempt to convert a non-str value to a str value for you, as well as creating only one string (for the result) in the process, not a series of temporary strings. For example,

print(f"My name is {name}. My name length is {len(name)}")
answered Feb 11, 2021 at 14:31

Comments

1

If you want to print a number you should use , insted of +, in this case len() returns an int so if you want to print the string length you should first convert it to a string.

I suggest using .format to print various type of data:

name = input("What is your name? ")
print("My name is {}. My name length is: {}".format(name,len(str(name))))
answered Feb 11, 2021 at 14:32

1 Comment

I'd suggest using an f-string and to drop the superfluous call to str (name is already a string): print(f'My name is {name}. My name length is: {len(name)}')

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.