Skip to content
Advertisement

How to capitalize only first letter of first word in a list

I want to capital only first letter of first word of list and remaining all words to be in lower case in ascending order of the length of word.

JavaScript

I want the result like this in ascending order of length.

In the are lines order printed reverse :

JavaScript

Actual output that I am trying to get:

JavaScript

Advertisement

Answer

Your code

JavaScript

does not work because each x is a word from z – it will never be equal to 0 so all that things added to s are lower case version of your words.


You can use enumerate to get the index of all elements in the list while iterating it.

The first element has to use .title() casing, all others .lower():

JavaScript

Output:

JavaScript

z = [ a.lower() if idx else a.capitalize() for idx, a in enumerate(z) ] is a list comprehension – as normal loop it would look like:

JavaScript

You can learn what python considers True for non-boolean values here: Truth-value-testing

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement