-4

I am reading this CSV file and adding its value to a list of a class. Can you kindly explain how is it possible to use the strip and split function like this?

ba = []
for line in cvsfile:
    j = line.split(',')
    num, f, s, b = [i.strip() for i in j]
    name = A(num, f, s, b)
    ba.append(name)

I am confused at this part.

j = line.split(',')
num, f, s, b = [i.strip() for i in j]

By the way, my class name is A.

Please explain. Thanks in advance. Sorry for the language as English is not my first.

Justin
  • 3
  • 2

2 Answers2

1

A CSV file has values separated by commas and the program is reading in the file line by line. Consider the following example

line = 'Val1,Val2,Val3' # consider this is a line in the CSV file

Now, using j = line.split(',') will split the line at the commas and return back a list of the values splitted.

When you split line at ,, you get a list equal to ['Val1', 'Val2', 'Val3'] which will now be assigned to j.

The .strip() method will remove any trailing or starting spaces from a string. For example,

s = '     hello      '
t = s.strip()
# now t is just equal to the string 'hello' without any spaces

[i.strip() for i in j] is creating a list of all values in j, but all spaces are removed from the values.

num, s, f, b = [i.strip() for i in j] is simply assigning the values inside the list to num, s, f and b.

Example,

a, b, c, d = [1, 2, 3, 4]

# the above line assigns a to 1, b to 2, c to 3 and d to 4
Riptide
  • 472
  • 3
  • 14
0

My friend, Amtthias, mentioned it is called list comprehension.

Justin
  • 3
  • 2