Last modified: Jan 10, 2023 By Alexander Williams
Finding the longest word in a string python (simple example)
In this article, we'll write an example that finds the longest word in a string.
Finding the longest word in a string python example:
#string string = "Python is a great langauge" #split string str_list = string.split() #sort list by length list_s = sorted(str_list, key=len) #print the last item of list print(list_s[-1])
as you can see "language" is the longest word in the string.
so, what we have done?
First, we've converted the string to a list by using the len() built-function, then sorted() built-function the list by length, finally, got the last item of the list.