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.
- Connect to your network directory.
- 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.
- 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.
- 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.
- Have your program print out the lines of the file, noting the newline character at the end of each string.
- 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.
- Convert the fourth line to an integer and assign the value to a variable.
- Have your program neatly print out each of the variables holding data from the file. Use a formatting string for each one.
- Create a for loop that executes as many times as the integer from the fourth line of the file.
- Add an import string statement to the top of your file.
- 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.
- 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.