Reputation: 21
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
Reputation: 489
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
Reputation: 11
updated_list= []
for i in input_list:
updated_list.append(i.capitalize())
print(updated_list)
Upvotes: 1
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
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
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
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
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