Page 144 -
P. 144
process and print
Code Magnets Solution
Your were to add the code magnets to your existing code to satisfy
the following requirements:
1. Create an empty list called man.
2. Create an empty list called other.
3. Add a line of code to remove unwanted whitespace from the
line_spoken variable.
4. Provide the conditions and code to add line_spoken to the
correct list based on the value of role.
5. Print each of the lists (man and other) to the screen.
Assign an empty list to
man = [] “man” and “other”.
other = []
try:
data = open('sketch.txt')
for each_line in data:
try:
Assign the
(role, line_spoken) = each_line.split(':', 1)
stripped string line_spoken = line_spoken.strip() The “strip()” method
back onto itself. removes unwanted
if role == 'Man': whitespace from a string.
man.append(line_spoken)
elif role == 'Other Man': Update one of the lists
“elif” means based on who said what.
“else if.” other.append(line_spoken)
except ValueError:
pass
data.close()
except IOError:
print('The datafile is missing!')
print(man)
Conclude by displaying the
print(other) processed data on screen.
108 Chapter 4