Meh Bej Meh Bej - 1 year ago 88
Python Question

Capitalizing words in (Python)?

I was trying to write something to capitalize each word in a sentence. And it works fine, as follows:

print " ".join((word.capitalize() for word in raw_input().strip().split(" ")))

If the input is 'hello world', the output would be :

Hello World

But I tried writing it differently as follows :

s = raw_input().strip().split(' ')
for word in s:
print ' '.join(s)

And its output would be wrong :

hello world

So what's wrong with that, why the result isn't the same ?! Thank you.

Answer Source

The problem in your code is that strings are immutable and you are trying to mutate it. So if you wont to work with loop you have to create new variable.

s = raw_input().strip().split(' ')
new_s = ''
for word in s:
    new_s += s.capitalize()
print new_s

Or, It would work if you use enumerate to iterate over list and update s:

s = raw_input().strip().split(' ')
for index, word in enumerate(s):
    s[index] = .capitalize()
print ' '.join(s)

But the best way to capitalize words in string is to use str.title() - method for capitalization of words in string:

s = 'hello word'