1

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:
    word.capitalize()
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.

Andriy Ivaneyko
  • 20,639
  • 6
  • 60
  • 82
Meher Béjaoui
  • 352
  • 2
  • 10
  • In your second program, you capitalize a copy of a word from s. Not the words in s itself. – SvbZ3r0 Jun 11 '16 at 07:23
  • 2
    Strings are immutable, so the string methods can't modify the original string, they always return a new string. Your 2nd code snippet isn't saving that new string. BTW, there's a simpler way to capitalize every word in a string: use the `str.title` method, eg `'hello world'.title()`. – PM 2Ring Jun 11 '16 at 07:23

3 Answers3

4

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'
print(s.title())
Andriy Ivaneyko
  • 20,639
  • 6
  • 60
  • 82
0

Strings are immutable and you are trying to update the same value which is not poassible.

Create a new string and update in that way.

s = raw_input().strip().split(' ')
st = ''
for word in s:
    st+= word.replace(word,word.capitalize())
print ''.join(st)

Or

print " ".join([i.capitalize() for i in raw_input().strip().split(" ")])
bhansa
  • 7,282
  • 3
  • 30
  • 55
0
print ' '.join([i.capitalize() for i in raw_input('Enter text here:').split(' ')])

This will solve you problem.

Rahul K P
  • 15,740
  • 4
  • 35
  • 52