5

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.

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.

If my raw input was "insert 0 5," wouldn't strip() turn it into "insert05" ?

CTLearn
  • 115
  • 2
  • 3
  • 9

3 Answers3

14

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

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'

Jesira ruhi
  • 11
  • 1
  • 4
soloidx
  • 729
  • 6
  • 12
3

Let's take an example, you take raw input

string=' I am a coder '

While you take input in form of a string, at first, strip() consumes input i.e. string.strip() makes it

string='I am a coder' 

since spaces at the front and end are removed. Now, split() is used to split the stripped string into a list i.e.

string=['I', 'am', 'a', 'coder'] 
0

Nope, that would be .remove(" "), .strip() just gets rid of white space at the beginning and end of the string.

Elliot Roberts
  • 910
  • 5
  • 10