find the longest word in a string in python

You can find the longest word in a string in Python by using the split() method to split the string into a list of words, then looping through the list to compare the lengths of each word and keeping track of the longest one. Here's an example:

main.py
def longest_word(string):
    # split the string into a list of words
    words = string.split()

    # initialize variable to keep track of longest word
    longest = ""

    # loop through the words and compare lengths
    for word in words:
        if len(word) > len(longest):
            longest = word
    
    return longest
332 chars
14 lines

Now you can call this function with a string and it will return the longest word:

main.py
my_string = "This is a sample string"
print(longest_word(my_string))  # Output: "sample"
89 chars
3 lines

gistlibby LogSnag