关于python中的raw_input.split()函数

问题描述

这一行在 python raw_input().split() 中究竟是如何工作的?

解决方法

首先,input() 提示用户输入。用户输入作为字符串的一系列字符。然后,split() 函数将来自用户的字符串分成单词列表(或字符组),并返回这些单词或分组字符的列表。默认情况下,列表中的每个元素都由空格分隔。请参阅以下示例。

words = input().split() # Typed "These are the input words"
print(words)

输出:

['These','are','the','input','words']

您还可以在 split() 方法中指定要拆分的空格以外的特定字符。例如,在本例中,输入字符串在出现 '1' 时被拆分。

words = input().split('1') # Typed "100120023104"
print(words)

输出:

['','00','20023','04']

请注意,split() 将省略返回列表中用于拆分输入字符串的请求字符(默认为空格 ' ')。

此外,raw_input() 在 Python3 中是 no longer supported。旧版本的 Python2 支持 raw_input()。现在,我们只在 Python3 中使用 input() 并且它的工作方式相同。如果您仍在使用 raw_input(),您应该将您的环境升级到 Python3。