在这段代码中,Python 中的 raw_input().strip().split() 如何工作?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/40598078/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How does raw_input().strip().split() in Python work in this code?
提问by CTLearn
Hopefully, the community might explain this better to me. Below is the objective, I am trying to make sense of this code given the objective.
希望社区可以更好地向我解释这一点。下面是目标,我试图在给定目标的情况下理解这段代码。
Objective: Initialize your list and read in the value of followed by lines of commands where each command will be of the types listed above. Iterate through each command in order and perform the corresponding operation on your list.
目标:初始化您的列表并读入后面的命令行的值,其中每个命令都属于上面列出的类型。按顺序遍历每个命令并对您的列表执行相应的操作。
Sample input:
样本输入:
12
insert 0 5
insert 1 10
etc.
Sample output:
示例输出:
[5, 10]
etc.
The first line contains an integer, n, denoting the number of commands. Each line of the subsequent lines contains one of the commands described above.
第一行包含一个整数 n,表示命令的数量。后续行的每一行都包含上述命令之一。
Code:
代码:
n = int(raw_input().strip())
List = []
for number in range(n):
args = raw_input().strip().split(" ")
if args[0] == "append":
List.append(int(args[1]))
elif args[0] == "insert":
List.insert(int(args[1]), int(args[2]))
So this is my interpretation of the variable "args." You take the raw input from the user, then remove the white spaces from the raw input. Once that is removed, the split function put the string into a list.
所以这是我对变量“args”的解释。您从用户那里获取原始输入,然后从原始输入中删除空格。删除后,split 函数会将字符串放入列表中。
If my raw input was "insert 0 5," wouldn't strip() turn it into "insert05" ?
如果我的原始输入是“insert 0 5”,会不会 strip() 把它变成“insert05”?
回答by soloidx
In python you use a split(delimiter)
method onto a string in order to get a list based in the delimiter that you specified (by default is the space character) and the strip()
method removes the white spaces at the end and beginning of a string
在python中,您split(delimiter)
在字符串上使用一个方法以获取基于您指定的分隔符(默认为空格字符)的列表,并且该strip()
方法删除字符串末尾和开头的空格
So step by step the operations are:
所以一步一步的操作是:
raw_input() #' insert 0 5 '
raw_input().strip() #'insert 0 5'
raw_input().strip().split() #['insert', '0', '5']
you can use split(';')
by example if you want to convert strings delimited by semicolons 'insert;0;5'
split(';')
如果要转换由分号 'insert;0;5' 分隔的字符串,可以通过示例使用
回答by Elliot Roberts
Nope, that would be .remove(" ")
, .strip()
just gets rid of white space at the beginning and end of the string.
不,那将是.remove(" ")
,.strip()
只是在字符串的开头和结尾去掉空格。