Python Count the Length of Each Word in a String
We will write a Python program to count the length of each word in a string. The program will first split the string into a list of words, then iterate over each word and calculate 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)
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:
word_lengths(s)The function accepts a stringsas a parameter.s.split()Split the stringsby spaces into a list of words.words。[len(word) for word in words]Use list comprehension to iteratewordsover each word in the list, calculate its length, and generate a list containing the lengths of all words.lengths。dict(zip(words, lengths))willwordsandlengthsCombine the two lists into a dictionary, where keys are words and values are the 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