Word Counter In python

I have tried to create a word counter in python, but my code fails to run.

word = input("Enter word or sentence")
input("Your word/ sentence has"+ len(word) + " letters")

Could you please help me fix the problem?

The current result is

TypeError: Can't convert "int" object into str implicity

Upvotes: 2

Views: 462

Answers (3)

Remi Guan
Remi Guan

Reputation: 22272

You could try the below code:

word = input("Enter word or sentence")
input("Your word/ sentence has"+ str(len(word)) + " letters")

Here, I'm using str(len(word)) instead of just len(word). Because len(word) returns a number and it's an int object.

And you're doing str_object + int_object, and Python doesn't understand what do you really want to do.

Let's see:

>>> len('foobar')
6
>>> type(len('foobar'))
<class 'int'>
>>> len('foobar') + 'foobar'
Traceback (most recent call last):
  File "<input>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'str'
>>> 

So you have to convert the int_object (which returned by len(word)) to a str object use str() function.

For example:

>>> str(len('foobar'))
'6'
>>> type(str(len('foobar')))
<class 'str'>
>>> str(len('foobar')) + 'foobar'
'6foobar'

You can also use str.format() instead of two +. Which can auto convert all objects to str, also it's more readable than your code.

So just use:

word = input("Enter word or sentence")
input("Your word/ sentence has {} letters".format(len(word)))

Upvotes: 1

user3652621
user3652621

Reputation: 3634

input takes a string input. If you wish to print, you must use print. len returns an integer value. Str converts it to string.

word = input("Enter word or sentence")
print("Your word/ sentence has"+ str(len(word)) + " letters")

Upvotes: 0

Clodion
Clodion

Reputation: 1017

You have an error:

word = input("Enter word or sentence")
print("Your word/ sentence has"+ str(len(word)) + " letters")

Or:

word = input("Enter word or sentence")
print("Your word/ sentence has", len(word), " letters")

Upvotes: 0

Related Questions