Search code examples
pythonstringlistcountstring-length

Output a list from a sentence and count characters for each word


I need to output a list with a character count in a 2 element list which gives the character count for each word:

[['How', 3], ['are', 3], ['you', 3], ['today', 5]]

I am using a function

def char(s):

    l = []  # list for holding your result

    # convert string s into a list of 2-element-lists
    s = text.split()
    s = [[word ,len(word)] for word in s.split()]
    print("Output:\n", s)
    print()
    return l


text = "How are you today"
l = char(text)
print()

but I am getting this output where it does total character count for each word instead of a specific count for each word:

[['How', 17], ['are', 17], ['you', 17], ['today', 17]]

Any help is appreciated, thank you.


Solution

  • Your problem is that you are counting the number of characters in text, but you have to count the characters in every word. In the end, you could even simplify your code as:

    def char(s):
        return [[word ,len(word)] for word in s.split()]
    

    Then you can call it by:

    text = "How are you today"
    l = char(text)
    print(l)
    

    Ouput:

    [['How', 3], ['are', 3], ['you', 3], ['today', 5]]