string - Capitalizing words in (Python)? -
this question has answer here:
i trying write capitalize each word in sentence. , works fine, follows:
print " ".join((word.capitalize() word in raw_input().strip().split(" ")))
if input 'hello world', output :
hello world
but tried writing differently follows :
s = raw_input().strip().split(' ') word in s: word.capitalize() print ' '.join(s)
and output wrong :
hello world
so what's wrong that, why result isn't same ?! thank you.
the problem in code strings immutable , trying mutate it. if wont work loop have create new variable.
s = raw_input().strip().split(' ') new_s = '' word in s: new_s += s.capitalize() print new_s
or, work if use enumerate iterate on list , update s
:
s = raw_input().strip().split(' ') index, word in enumerate(s): s[index] = .capitalize() print ' '.join(s)
but best way capitalize words in string use str.title() - method capitalization of words in string:
s = 'hello word' print(s.title())
Comments
Post a Comment