Python Count the Length of Each Word in a String
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
)
(
result
)
Code analysis:
word_lengths(s)The function takes a stringsas its argument.s.split()Add the firstsSplit into a list of words by spaceswords。[len(word) for word in words]Use a list comprehension to iterate overwordseach word in the list and compute its length, producing a list containing all word lengthslengths。dict(zip(words, lengths))data to the child component viawordsandlengthsCombine the two lists into a dictionary where the keys are the words and the values are their corresponding lengths.- Finally, the function returns this dictionary.
Output result:
Example
{
'Hello'
:
5
,
'world'
:
5
,
'this'
:
4
,
'is'
:
2
,
'a'
:
1
,
'test'
:
4
}
Python3 Examples