Python: How can I calculate the average word length in a sentence using the .split command?

后端 未结 9 1685
甜味超标
甜味超标 2021-01-03 11:40

new to python here. I am trying to write a program that calculate the average word length in a sentence and I have to do it using the .split command. btw im using python 3.2

9条回答
  •  日久生厌
    2021-01-03 12:19

    In Python 3 (which you appear to be using):

    >>> sentence = "Hi my name is Bob"
    >>> words = sentence.split()
    >>> average = sum(len(word) for word in words) / len(words)
    >>> average
    2.6
    

提交回复
热议问题