1

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.

Zero Piraeus
  • 56,143
  • 27
  • 150
  • 160
Rob Alsod
  • 2,635
  • 3
  • 19
  • 18

2 Answers2

4

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 ''.

Community
  • 1
  • 1
Zero Piraeus
  • 56,143
  • 27
  • 150
  • 160
0

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']
Community
  • 1
  • 1
KGo
  • 18,536
  • 11
  • 31
  • 47
  • In Python 3.x, `map()` [returns an iterator](http://docs.python.org/3.3/whatsnew/3.0#views-and-iterators-instead-of-lists) rather than a list, so your last line would need to be `list(map(up, words))`. By the way, `map()` doesn't avoid loops but merely hides them (just like list comprehensions) - usually, as in this case, with a significant performance penalty over listcomps. – Zero Piraeus Aug 07 '13 at 14:14