Python Count the Length of Each Word in a String

Document 对象参考手册Python3 Examples

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)

Code analysis:

  1. word_lengths(s)The function accepts a stringsas a parameter.
  2. s.split()Split the stringsby spaces into a list of words.words。
  3. [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。
  4. dict(zip(words, lengths))willwordsandlengthsCombine the two lists into a dictionary, where keys are words and values are the 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 对象参考手册Python3 Examples

Other Extensions