Sai Hemanth Varala
Sai Hemanth Varala

Reputation: 21

How to get list using for loop in python and we have to capitalize the first letter of the every element?

You are given a list of string elements and asked to return a list which contains each element of the string in title case or in other words first character of the string would be in upper case and remaining all characters in lower case

Sample Input:

['VARMA', 'raj', 'Gupta', 'SaNdeeP']

Sample Output

['Varma', 'Raj', 'Gupta', 'Sandeep']

Upvotes: 0

Views: 10238

Answers (7)

Naresh Kumar
Naresh Kumar

Reputation: 489

Below code is working fine !

input_list = ['VARMA', 'raj', 'Gupta', 'SaNdeeP']
output=[] 
for i in range(len(input_list)): # length of input 
    output.append(input_list[i][0].upper() + input_list[i][1:].lower()) # first character as uppercase and remaining characters a lower case
print(output) 

Output

['Varma', 'Raj', 'Gupta', 'Sandeep']

Upvotes: 0

Ajay
Ajay

Reputation: 11

updated_list= []

for i in input_list:
    updated_list.append(i.capitalize())
    
print(updated_list)

Upvotes: 1

SHAHEED Khan
SHAHEED Khan

Reputation: 1

You can you capitalize() method of string and list comprehension as followings:

data = [ ' Verma' ,  ' raj ' ,  ' Gupta ' ,  ' SaNdeeP ' ]
capitalized = [ a.capitalize( )  for a in data ]
print ( capitalized ) 

Upvotes: 0

Krishna Singhal
Krishna Singhal

Reputation: 661

lt = ['VARMA', 'raj', 'Gupta', 'SaNdeeP']

Using Map Function

print(list(map(lambda x : x.title(),lt)))
Output - ['Varma', 'Raj', 'Gupta', 'Sandeep']

Upvotes: 0

deadshot
deadshot

Reputation: 9061

Using str.title()

a = ['VARMA', 'raj', 'Gupta', 'SaNdeeP']
res = [x.title() for x in a]
print(res)
#['Varma', 'Raj', 'Gupta', 'Sandeep']

Upvotes: 0

Tim Biegeleisen
Tim Biegeleisen

Reputation: 521457

The answer by @Harun is probably the best one here, but as an alternative, and a more general answer, we can consider using re.sub with a callback function:

data = ['VARMA', 'raj', 'Gupta', 'SaNdeeP']
capitalized = [re.sub(r'^(.)(.*)$', lambda m: m.group(1).upper() + m.group(2).lower(), a)
    for a in data]
print(capitalized)

This prints:

['Varma', 'Raj', 'Gupta', 'Sandeep']

Upvotes: 0

Harun Yilmaz
Harun Yilmaz

Reputation: 8558

You can use capitalize() method of string and list comprehension as followings:

data = ['VARMA', 'raj', 'Gupta', 'SaNdeeP']

capitalized = [a.capitalize() for a in data]

print(capitalized)

Upvotes: 5

Related Questions