- The kids.txt file contains comma separated lines. Here is the first line of
this file:
Samantha,F,5
- To extract the fields (name, gender, age) from this line, we use the split method,
which is called from an str object:
line = "Samantha,F,5"
fields = line.split( )
print(fields)
# Output:
["Samantha", "F", "5"]
line.split( ) returns a Python list, which is shown in the output.
Here is a table showing the items and corresponding indices in the list:
Items: | "Samantha" |
"F" | "5" |
Indices: | 0 |
1 | 2 |
- Items in the list are extracted by index. Notice that the indices are
zero-based; they start at 0, not 1. (I have previously mentioned that computer
scientists start counting with zero.)
fields = ["Samantha", "F", "5"]
name = fields[0]
gender = fields[1]
age = int(fields[2])
print(name, gender, age)
# Output:
Samantha F 5
- A safer way to extract the fields from a line is to use the the str strip method,
which removes leading and training white space from the field. In particular, the
end of a line read from a file is the \n character:
line = "Samantha , F , 5\n"
fields = line.strip( )
name = fields[0].strip( )
gender = fields[1].strip( )
age = int(fields[2].strip( ))
print(name, gender, age)
# Output:
Samantha F 5
- Here are the Kids Examples:
Input file: kids.txt
- What is the average age of all kids? Ans:
kids1.txt
- What is the average age of the girls? Ans:
kids2.txt
- What is the maximum age of the boys? Ans:
kids3.txt
- Zipfile of all examples for these notes:
sequential-processing.zip