Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python Count the Length of Each Word in a String

Python Count the Length of Each Word in a String

Document Object Reference Manual Python3 Examples

We will write a Python program that counts the length of each word in a string. The program first splits the string into a list of words, then iterates over each word and computes its length.

Example

def

word_lengths

(

s

)

:

    words

=

s.

split

(

)

    lengths

=

[

len

(

word

)

for

word

in

words

]

   

return

dict

(

zip

(

words

,

lengths

)

)

Example string

text

=

"Hello world this is a test"

result

=

word_lengths

(

text

)

print

(

result

)

Code analysis:

  1. word_lengths(s) The function takes a string s as its argument.
  2. s.split() Add the first s Split into a list of words by spaces words。
  3. [len(word) for word in words] Use a list comprehension to iterate over words each word in the list and compute its length, producing a list containing all word lengths lengths。
  4. dict(zip(words, lengths)) data to the child component via words and lengths Combine the two lists into a dictionary where the keys are the words and the values are their corresponding lengths.
  5. Finally, the function returns this dictionary.

Output result:

Example

{

'Hello'

:

5

,

'world'

:

5

,

'this'

:

4

,

'is'

:

2

,

'a'

:

1

,

'test'

:

4

}

Document Object Reference Manual Python3 Examples