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.

z=['The' ,'lines', 'are', 'printed', 'in', 'reverse', 'order']
z.sort(key=len) 
print(" ".join(x.lower() for x in z))

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

In the are lines order printed reverse :

z=['The' ,'lines', 'are', 'printed', 'in', 'reverse', 'order']
# i tried like this 
z.sort(key=len)
s=[]
for x in z:
     if (x==0):
        s.append(z[0].capitalize())
     else:
        s.append(z[x].lower())

Actual output that I am trying to get:

In the are lines order printed reverse

Advertisement

Answer

Your code

for x in z:    # ['in', 'The', 'are', 'lines', 'order', 'printed', 'reverse']
     if (x==0):
        s.append(z[0].capitalize())
     else:
        s.append(z[x].lower())

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():

z= ['The' ,'lines', 'are', 'printed', 'in', 'reverse', 'order']
z.sort(key=len) 

# reformat capitalization based in index, any number != 0 is true-thy
z = [ a.lower() if idx else a.capitalize() for idx, a in enumerate(z) ]

print(" ".join(z))

Output:

In the are lines order printed reverse

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:

s = []
for idx, word in enumerate(z):
    if idx:   # any idx > 0 is True-thy
        s.append(word.lower())
    else:
        s.append(word.capitalize())
# print the joined s 

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