9

I am trying to get the length of each word in a sentence. I know you can use the "len" function, I just don't know how to get the length of each word.

Instead of this

>>> s = "python is pretty fun to use"
>>> len(s)
27
>>>

I'd like to get this

6, 2, 6, 3, 2, 3

which is the actual length of every word.

Josh Durham
  • 1,572
  • 1
  • 16
  • 27
Reymy
  • 113
  • 2
  • 2
  • 7

4 Answers4

16

Try this, using map() for applying len() over each word in the sentence, understanding that split() creates a list with each word in the sentence:

s = "python is pretty fun to use"
map(len, s.split())       # assuming Python 2.x
list(map(len, s.split())) # assuming Python 3.x

Or alternatively, you can use a list comprehension for the same effect:

[len(x) for x in s.split()]

In both cases the result is a list with the length of each word in the sentence:

[6, 2, 6, 3, 2, 3]
Óscar López
  • 215,818
  • 33
  • 288
  • 367
8

Use map1 and str.split:

>>> s = "python is pretty fun to use"
>>> map(len, s.split())
[6, 2, 6, 3, 2, 3]
>>>

1Note: map returns an iterator in Python 3. If you are using that version, you may want to place it in list to get a list of integers like the Python 2 map returns:

>>> # Python 3 interpreter
>>> s = "python is pretty fun to use"
>>> map(len, s.split())
<map object at 0x02364ED0>
>>> list(map(len, s.split()))
[6, 2, 6, 3, 2, 3]
>>>
7

Use this:

s = "python is pretty fun to use"
[len(x) for x in s.split()]

example output:

>>> [len(x) for x in s.split()]
[6, 2, 6, 3, 2, 3]

What's going on in the background?

s.split() breaks on the white space in the string and returns each word in the sentence in a list:

>>> s.split()
['python', 'is', 'pretty', 'fun', 'to', 'use']

Then we take the len() of each of those words to get the word's length. After that, we take each length and append it to a list so that it can be conveniently returned as the result.

That all happens in this list comprehension:

[len(x) for x in s.split()]

Still a little confused? This is conceptually the same thing just broken down more explicitly:

results = []
for x in s.split():
    word_length = len(x)
    results.append(word_length)
print results 

If you'd like them printed out separately, like in your question, use:

for x in [len(x) for x in s.split()]: 
    print x
agconti
  • 15,820
  • 15
  • 69
  • 108
0

iCodez is right - but it requires a few minor adjustments from script form.

s = 'python is pretty fun to use'
li = list(map(len, s.split()))

then type into the shell or print statement:

print(li)