Problem Statement
You are given a string S. Your task is to capitalize each word of S.
Input Format
A single line of input containing the string, S.
Constraints
0
The string consists of alphanumeric characters and spaces.
Output Format
Print the capitalized string, S.
Sample Input
hello world
Sample Output
Hello World
1、首先我尝试写程序,我的代码如下:
[print(str.capitalize(s), end=' ') for s in input().split()]
结果运行错误,因为我忽略了多个空格的影响
2、用正则表达式解决,
import re
print re.sub(r'\w+', lambda x : x.group(0).capitalize(), raw_input())
运行成功
3、官方提供的答案,真是令人意外啊!!!
print ' '.join(word.capitalize() for word in raw_input().split(' '))
通过这种方式能解决多个空格的问题,我不能明白为何能这么作,只能猜测join函数能记住split函数分出的空格。
经测试,这样也是可以的,如下:
a=[word.capitalize() for word in raw_input().split(' ')]
print ' '.join(a)