CS 151: Lab #5

Lab Exercise 5: More with Strings and Files

The purpose of this lab time is to give you more practice with python and writing programs. The focus this week will be on reading files, manipulating strings, and convert strings to numbers.


  1. Connect to your network directory.
  2. Create a new file in BBEdit or whatever editor you wish. Save the file as stringfun.py. Download the file system0 to your working directory.
  3. Define a main function with no arguments. Inside the main function, ask the user for a filename and open the file for reading. Put the file open function inside a try/except statement to catch errors gracefully.
  4. Once the file is open, use the method readlines() to read the file and store the list in a variable. Use a variable name that is meaningful.
  5. Have your program print out the lines of the file, noting the newline character at the end of each string.
  6. Assign each of the first three lines to a different variable, removing the newline character (the last character in the string) in the process. Remember, you can use the slice notation a[:-1] to refer to all of the characters in a string except the last one.
  7. Convert the fourth line to an integer and assign the value to a variable.
  8. Have your program neatly print out each of the variables holding data from the file. Use a formatting string for each one.
  9. Create a for loop that executes as many times as the integer from the fourth line of the file.
  10. Add an import string statement to the top of your file.
  11. Inside the for loop, put a call to the method replace in the string package. You'll need to use the syntax string.replace(). The function replace takes three arguments: a base string, a substring to be replaced, and the string to replace it with. The function returns the result of its operation and you can store it back in the variable holding the base string using an assignment. Do so. Each time through the loop, print out the contents of the variable holding the base string.
  12. Ask the user for a filename, and write the resulting base string to the file. Try running the string using your linearC.py from the last lab.

Once you've finished the above exercise, get started on the next project.