find the shortest word in a string in python

You can split the string into individual words using the split() method, and then use a loop to iterate through the words to find the shortest one. Here's an example:

main.py
def shortest_word(s):
    # split the string into individual words
    words = s.split()
    
    # initialize shortest_word to be the first word in the list
    shortest_word = words[0]
    
    # iterate through the rest of the words to find the shortest one
    for word in words[1:]:
        if len(word) < len(shortest_word):
            shortest_word = word
    
    return shortest_word
394 chars
14 lines

Here's how you can use the function:

main.py
s = "hello world this is a test"
print(shortest_word(s))  # Output: "a"
72 chars
3 lines

gistlibby LogSnag