find the kth longest word in a string in python

To find the kth longest word in a string, you can follow these steps:

  1. Convert the string into a list of words using split() function.
  2. Sort the list of words by their length in descending order using sorted() and lambda function.
  3. Return the element at index k-1.

Here's the code to achieve this:

main.py
def kth_longest_word(s, k):
    words = s.split()
    words.sort(key=lambda word: len(word), reverse=True)
    return words[k-1]
129 chars
5 lines

Let's test the function with an example:

main.py
s = "The quick brown fox jumps over the lazy dog"
k = 3
print(kth_longest_word(s, k))  # Output: jumps
103 chars
4 lines

In this example, the 3rd longest word in the string is "jumps" and the function correctly returns it.

gistlibby LogSnag