Python split()String包含空格的列表

Wal*_*tob 0 python string-split

user_words = raw_input()
word_list = user_words.split()
user_words = []
for word in word_list:
    user_words.append(word.capitalize())
user_words = " ".join(user_words)
print(user_words)
Run Code Online (Sandbox Code Playgroud)

电流输出:

Input:
hello  world(two spaces in between)

Output:
Hello World

Desired Output:

Input:
hello  world(two spaces in between)

Output:
Hello  World(two spaces in between)

注意:我希望能够用空格分割字符串,但仍然在用户输入的原始字符串中的单词之间有多余的空格.

Joh*_*ooy 8

如果您使用空格字符进行拆分,您将''在列表中获得额外收益

>>> "Hello  world".split()
['Hello', 'world']
>>> "Hello  world".split(' ')
['Hello', '', 'world']
Run Code Online (Sandbox Code Playgroud)

那些在连接后再次产生额外的空间

>>> ' '.join(['Hello', '', 'world'])
'Hello  world'
Run Code Online (Sandbox Code Playgroud)