Reputation: 1
Having a hard time understanding what is happening in this snippet of code. Particularly with the 2nd line of code.
for line in infile:
data = line.strip('\n').split(':')
user_dict[data[0]] = data[1]
Upvotes: 0
Views: 97
Reputation: 5704
Basically line.strip('\n')
removes leading consecutive newlines and trailing consecutive newlines, but leaves embedded newlines alone. from line; and then split(':')
separates anywhere ":
" is.This is then stored as a list in the variable named data
.
Upvotes: 0
Reputation: 9727
It parses a file having this structure:
a:52
b:hi
key:value
for line in infile:
is a loop for each line in the file. Each line (except for the last maybe) ends with new-line symbol \n
.
line.strip('\n')
removes the new-line symbol.
.split(':')
splits the string into strings there were separated by :
. For example: "qwe:rty:uio".split(':') -> ["qwe", "rty", "uio"]
user_dict[data[0]] = data[1]
obviously saves the data into the dicionary user_dict
taking the first string as a key, and second one as a value.
For the file mentioned above this code creates the following dictionary:
{"a": "52", "b": "hi", "key": "value"}
Upvotes: 1
Reputation: 1
data = line.strip('\n').split(':')
There are two string functions in one line. You also can separate the calls. This should be the same:
my_line = line.strip('\n')
my_line1 = my_line.split(':')
line.strip --> removes the new line character at the end of a line line.split(':') --> splits the values at colon character and return a list of each record
It is easier to understand with concrete values.
Your file look like this and you loop through each line. Name: Paul Age: 18 Gender: Male
At the end of each line you have a "new line" character which will remove line.strip('\n'). Then you split the values at ":" You finally create a dictionary (line 3) where key is the left side and the value is the right side. dict['Name'] = 'Paul' dict['Age'] = '18'
Upvotes: 0
Reputation: 6762
line.strip('\n')
will remove all the newlines from the string.
and
split(':')
will split your string using ':' into array of strings.
Upvotes: 0
Reputation: 443
Above code is storing the file into the dictionary. Content of the file is like below
key1:value1
key2:value2
.
.
.
key3:value3
Second line is stripping off the \n character from the line and then splitting the each line by : character. However you should try to understand and debug the code line by line
Upvotes: 0
Reputation: 337
line.strip('\n')
is removing all the \n (new line) from the string and the split(':')
it is going to split your string using :
as the delimeter into an array of strings.
Upvotes: 0
Reputation: 7308
The line sets the variable data
equal to the string represented by the variable line
with the new line character '\n'
removed and then split anywhere a :
occurs.
Upvotes: 1