Reputation: 347
s = ['my', 'name']
I want to change the 1st letter of each element in to Upper Case.
s = ['My', 'Name']
Upvotes: 33
Views: 43967
Reputation: 123393
It probably doesn't matter, but you might want to use this instead of the capitalize()
or title()
string methods because, in addition to uppercasing the first letter, they also lowercase the rest of the string (and this doesn't):
s = map(lambda e: e[:1].upper() + e[1:] if e else '', s)
Note: In Python 3, you'd need to use:
s = list(map(lambda e: e[:1].upper() + e[1:] if e else '', s))
because map()
returns an iterator that applies function to every item of iterable instead of a list
as it did in Python 2 (so you have to turn it into one yourself).
Upvotes: 6
Reputation: 262919
You can use the capitalize() method:
s = ['my', 'name']
s = [item.capitalize() for item in s]
print s # print(s) in Python 3
This will print:
['My', 'Name']
Upvotes: 30
Reputation: 985
Both .capitalize() and .title(), changes the other letters in the string to lower case.
Here is a simple function that only changes the first letter to upper case, and leaves the rest unchanged.
def upcase_first_letter(s):
return s[0].upper() + s[1:]
Upvotes: 57
Reputation: 20419
You can use
for i in range(len(s)):
s[i]=s[i].capitalize()
print s
Upvotes: 0
Reputation: 10571
You can use 'my'.title()
which will return 'My'
.
To get over the complete list, simply map over it like this:
>>> map(lambda x: x.title(), s)
['My', 'Name']
Actually, .title()
makes all words start with uppercase. If you want to strictly limit it the first letter, use capitalize()
instead. (This makes a difference for example in 'this word' being changed to either This Word
or This word
)
Upvotes: 14