Question: In this problem, you will write a function named process _ line ( ) that accepts a string representing a sequence of distinct values. The

In this problem, you will write a function named process_line() that accepts a string representing a sequence of distinct
values. The function will split the string into individual strings, coerce each string into the desired data type, and will then
return the results as a list.
The function should accept three parameters named line, schema, and sep.
line should contain a string that is to be split into separate values.
schema should be a list of data types indicating the desired types for each of the values in line.
sep should be a string indicating the character used to separate the different values in line.
As an example, consider the following string:
test_line ='6,174,Blah,Hello World,7.37'
We wish to separate this into smaller strings by splitting it at commas. We will then coerce each resulting token into the
appropriate data type according to the following schema:
test_schema =[int, int, str, str, float]
The function call process_line(test_line, test_schema, ',') should return the following list:
[6,174, 'Blah', 'Hello World', 7.37]
Write a function named process_line() that accepts three parameters line, schema, and sep as described above.
The function should perform the following steps:
1. Use the split() method to split the string line on the character provided by sep. Store the resulting list in a
variable named tokens.
2. Create an empty list named result.
3. Simultaneously loop over the elements of the lists tokens and schema (which are intended to have the same
number of elements). Each time the loop executes, perform the following steps:
a. Store the current element of tokens in a variable named t.
b. Store the current element of schema in a variable named dt.
c. Note that dt will contains a data type, while t will hold a string. Coerce t into a value with the desired
data type using dt(t). Append the converted value into the list result.
4. Return result.
We will apply this function in the next example, but we will first test it to make sure that it is working correctly.
In a new code cell, create the following objects:
test_schema =[int, int, str, str, float]
test_line ='6,174,Blah,Hello World,7.37'
Use the process_line() function to split the string test_line at the commas, coercing the individual tokens into
the data types stored in test_schema. Print the result.

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Programming Questions!