简体   繁体   中英

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 

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?'
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: this There is, however, an easier way to do what you want: s = s.title()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM