Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing lengths of words in strings

Need to find the longest word in a string and print that word. 1.) Ask user to enter sentence separated by spaces. 2.)Find and print the longest word. If two or more words are the same length than print the first word.

this is what I have so far

def maxword(splitlist):      #sorry, still trying to understand loops
    for word in splitlist:
        length = len(word)
        if ??????

wordlist = input("Enter a sentence: ")
splitlist = wordlist.split()

maxword(splitlist)

I'm hitting a wall when trying to compare the lenghts of words in a sentance. I'm a student who's been using python for 5 weeks.

like image 211
Mixtli Avatar asked Dec 08 '25 04:12

Mixtli


1 Answers

def longestWord(sentence):
    longest = 0   # Keep track of the longest length
    word = ''     # And the word that corresponds to that length
    for i in sentence.split():
        if len(i) > longest:
            word = i
            longest = len(i)
    return word

>>> s = 'this is a test sentence with some words'
>>> longestWord(s)
'sentence'
like image 143
Cory Kramer Avatar answered Dec 10 '25 19:12

Cory Kramer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!