unleu
unleu

Reputation: 13

Capitalize first character of a word in a string

How is one of the following versions different from the other?

  1. The following code returns the first letter of a word from string capitalize:

    s = ' '.join(i[0].upper() + i[1:] for i in s.split())
    
  2. The following code prints only the last word with every character separated by space:

    for i in s.split():
        s=' '.join(i[0].upper()+i[1:]
        print s
    

Upvotes: 0

Views: 112

Answers (2)

zondo
zondo

Reputation: 20336

for i in s.split():` 

At this point i is a word.

s = ' '.join(i[0].upper() + i[1:])

Here, i[0] is the first character of the string, and i[1:] is the rest of the string. This, therefore, is a shortcut for s = ' '.join(capitalized_s). The str.join() method takes as its argument a single iterable. In this case, the iterable is a string, but that makes no difference. For something such as ' '.join("this"), str.join() iterates through each element of the iterable (each character of the string) and puts a space between each one. Result: t h i s There is, however, an easier way to do what you want: s = s.title()

Upvotes: 1

timgeb
timgeb

Reputation: 78700

For completeness and for people who find this question via a search engine, the proper way to capitalize the first letter of every word in a string is to use the title method.

>>> capitalize_me = 'hello stackoverlow, how are you?'
>>> capitalize_me.title()
'Hello Stackoverlow, How Are You?'

Upvotes: 2

Related Questions