Home > OS >  How to count the length of a word in a sentence using python
How to count the length of a word in a sentence using python

Time:12-18

I want to count the length of a word in a sentence

Input: Hi Hello How Are You
Output: 2 5 3 3 3

s=input("Enter the sentence:\n")
a=list(map(len, s.split()))
print(a)

I already tried this code which in fact returns the correct output but it's a list i.e- Input-Hi Hello Output-[2,5]

I don't want it as a list, I want it as Input-Hi Hello Expected Output- 2 5

CodePudding user response:

This should give you what you need:

s=input('Enter a sentence: ')
print(*map(len, s.split()))

CodePudding user response:

sentence = "Hello how are you"

for word in sentence.split(' '):
    print(len(word))

Here a simple loop.

CodePudding user response:

The join function along with map may help to print the list like this

s=input("Enter the sentence:\n")
a=list(map(len, s.split()))
print(" ".join(map(str, a))) 

as the map functon heps in converting elements to string and join to separate the using space.

  • Related