I am trying to find the maximum length word in a sentence

Viewed 223

I am trying to find the maximum length word in a sentence, like

a = "my name is john and i am working in STACKOVERFLOWLIMITED"

To fetch the largest word in this sentence, I am trying something like

c = a.split(',')

c = ['my', 'name', 'is', 'john', 'and', 'i', 'am', 'working', 'in', 'STACKOVERFLOWLIMITED']

When I am trying to print max (C)

output - 'working'

Why the output doesn't contain "STACKOVERFLOWLIMITED" as the longest word in that sentence?

2 Answers

that's why the working word considers as the maximum alphabetically word, not length. try this :

result = max(a.split(), key=len)
print(result)

another way is...

sorted([(x,len(x)) for x in c],key= lambda x: x[1])[-1][0]
Related