Question

I need to write a program that can capitalise each word in a sentence (which is stored as a list of words), without affecting the capitalisation of other parts of the sentence.

Let's say, for example, the sentence is 'hello, i am ROB ALSOD'. In a list, this would be:

['hello,','i','am','ROB','ALSOD']

I understand that I could loop through and use the str.title() method to title them, but this would result in:

['Hello,','I','Am','Rob','Alsod']

Notice the difference? The effect I am going for is:

['Hello,','I','Am','ROB','ALSOD']

In other words, I want to keep other capitalised letters the same.

Was it helpful?

Solution

That's a one-liner, using list comprehensions and string slicing:

>>> words = ['hello,','i','am','ROB','ALSOD']
>>> [word[:1].upper() + word[1:] for word in words]
['Hello,', 'I', 'Am', 'ROB', 'ALSOD']

It uppercases word[:1] (everything up to and including the first character) rather than word[0] (the first character itself) in order to avoid an error if your list contains the empty string ''.

OTHER TIPS

While Zero Piraeus's answer is correct, I'd be down for a more functional syntax that avoids loops.

>>> words = ['hello,','i','am','ROB','ALSOD']
>>> def up(word): return word[:1].upper() + word[1:]
>>> map(up, words)
['Hello,', 'I', 'Am', 'ROB', 'ALSOD']
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top