Checkpoint 9.14.1.
Q-1: Most list methods return ______, where string methods generally return a new string.
None.word = word.strip()
t = t.sort() # WRONG!
sort returns None, the next operation you perform with t is likely to fail.pop, remove, del, or even a slice assignment.append method or the + operator. But don't forget that these are right:t.append(x)
t = t + [x]
t.append([x]) # WRONG!
t = t.append(x) # WRONG!
t + [x] # WRONG!
t = t + x # WRONG!
sort that modifies the argument, but you need to keep the original list as well, you can make a copy.orig = t[:]
t.sort()
sorted, which returns a new, sorted list and leaves the original alone. But in that case you should avoid using sorted as a variable name!split , and files.From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008
startswith and simply look at the first word of the line to determine if we are interested in the line at all. We can use continue to skip lines that don't have “From” as the first word as follows:rstrip to remove the newline at the end of the file. But is it better?print statement. The best place to add the print statement is right before the line where the program failed and print out the data that seems to be causing the failure.words right before line five. We even add a prefix “Debug:” to the line so we can keep our regular output separate from our debug output.for line in fhand:
words = line.split()
print('Debug:', words)
if words[0] != 'From' : continue
print(words[2])
Debug: ['X-DSPAM-Confidence:', '0.8475']
Debug: ['X-DSPAM-Probability:', '0.0000']
Debug: []
Traceback (most recent call last):
File "search9.py", line 6, in <module>
if words[0] != 'From' : continue
IndexError: list index out of range
split the line into words. When the program fails, the list of words is empty []. If we open the file in a text editor and look at the file, at that point it looks as follows:X-DSPAM-Result: Innocent X-DSPAM-Processed: Sat Jan 5 09:14:16 2008 X-DSPAM-Confidence: 0.8475 X-DSPAM-Probability: 0.0000 Details: http://source.sakaiproject.org/viewsvn/?view=rev&rev=39772
word[0]) to check to see if it matches “From”, we get an “index out of range” error.continue to skip to the next line in the file.continue statements as helping us refine the set of lines which are “interesting” to us and which we want to process some more. A line which has no words is “uninteresting” to us so we skip to the next line. A line which does not have “From” as its first word is uninteresting to us so we skip it.words[0] will never fail, but perhaps it is not enough. When we are programming, we must always be thinking, “What might go wrong?”https://docs.python.org/library/stdtypes.html#common-sequence-operationshttps://docs.python.org/library/stdtypes.html#mutable-sequence-types