Find the length shortest word in a string in Python

Viewed 11357

I'm working on an assignment where I have to have someone input a string of words and my program is supposed to then pick out the length of the shortest and longest word in that string. I've successfully had it pick out the length of the longest word:

def longWord(string):
    alist = []
    length = 0
    for letter in string:
        if letter != " ":
            length +=1
        else:
            alist.append(length)
            length = 0
        return alist

So if the input is "happy day", my print function tells me that the longest word is 5 characters.

However, for the life of me I can't figure out how to write something that will pick out the length of the shortest word in the input string. How would I do this?

3 Answers

Easiest way to find the smallest word is to use min function along with the len function as key :

>>> s = 'Happy day'
>>> l = s.split()
>>> min(l, key=len)
=> 'day'

Similarly, for finding the longest word, use max :

>>> max(l, key=len)
=> 'Happy'

Now the easy part, for getting its length, enclose the above in len function :

>>> len(min(l, key=len))
=> 3

If you only want to know the length, and not the actual word, you can use:

def length(s):
    l = map(len, s.split())
    return max(l), min(l)

You can try this:

s = "This is a template sentence"
final_data = sorted(s.split(), key=len)
minimum = final_data[0]
maximum = final_data[-1]
Related