# Finding longest word in a sentence

A problem from Coderbyte. Find the longest word in a sentence after removing the punctuations and if two or more words are of same length return the first word

Below is my solution:

def cleanWord(word):
# To remove punctuations
punctuations = ['!','.','\'','"',',','&']
new_word = ''

for c in word:
if c in punctuations:
continue
else:
new_word += c

return new_word

def LongestWord(sen):

words = sen.split(' ')

word_lengths = {}
# finding length of each word
for word in words:
clean_word = cleanWord(word)
if len(clean_word) not in word_lengths.keys():
word_lengths[len(clean_word)] = word

longest_word_length = max(word_lengths.keys())
longest_word = word_lengths[longest_word_length]
#print(word_lengths)

return longest_word


def cleanWord(word):
# To remove punctuations


The comment is a better name without_punctuation. Also you should be following snake case as per PEP-8.

Much of your logic in the longest word function can be handled by max with a key function. The overall solution can be written like so.

def without_punctuation(text):
translator = str.maketrans('','',string.punctuation)
return text.translate(translator)

def longest_word(sentence):
words = without_punctuation(sentence).split()
return max(words,key=len)

• If the sentence is written like your code, i.e., without the standard space after commas (rather bad for someone pointing out PEP 8 :-), then you incorrectly combine words. Commented Mar 1, 2021 at 22:14