Homework for Week 5
After this week you can
- Perform common operations with strings
- Use Python's string functions
- Open and close files
- Read and process files line by line
- Write files
Strings
Python comes with a robust set of tools for text processing, the basis for which is the string data type. A string is a sequence of characters. We can read, index, slice, loop over, concatenate, compare, modify, strip, parse strings, as well as perform many other operations with them. Strings are often used in conjunction with files which we look at next week.
Slides in English
Textbook in English
Files
The basics of manipulating files include opening a file, reading data from or writing data to it, and closing the file. Often the files are text files and are made up of lines that are more or less human-readable. Such files are processed line by line, applying the needed operations on each line after it is read.
Slides in English
Textbook in English
Quiz
Go to Moodle and solve the quiz on strings and files.
Examples
Strings are useful in situations where we need to process textual data.
Personal identification code
Estonian personal identification code is a number that is unique for each citizen. The national ID card, its associated certificates, and digital signatures use personal identification codes. The code contains information about the person's gender and date of birth. Since the personal identification code is unique, it is possible to identify persons by their codes.
The code consists of 11 digits, generally written without whitespaces or other delimiters. It has the form GYYMMDDSSSC, where G shows the gender and birth century (odd numbers for male, even numbers for female; 1-2 for individuals born in the 19th century, 3-4 for the 20th century, and 5-6 for the 21st century). SSS is a serial number uniquely identifying people born on the same date, and C is the checksum digit.
The following program prompts the user for an identification code, finds the person's birth date from the code, and prints it out in the format dd.mm.yyyy:
code = input("Please enter a personal identification code: ") #For example: 48007140350 date = code[5] + code[6] month = code[3] + code[4] if code[0] == "1" or code[0] == "2": century = "18" elif code[0] == "3" or code[0] == "4": century = "19" else: century = "20" year = century + code[1] + code[2] print("The birthday of the person with the code", code, "is", date+"."+month+"."+year)
Note the use of + operations here, both in standalone expressions and in the print statement.
Room number from address
The following program prompts for an address. The program finds and prints the room number in the address, assuming that the address is entered in the form of street_name building_number-room_number, town_name; e.g., Narva mnt 18-2039, Tartu.
address = input("Enter address: ") fpos = address.find("-") lpos = address.find(",", fpos) room = address[fpos+1:lpos] print("Room number is", room)
The find command allows performing sequential searches in a string. Each subsequent search begins at the position where the previous search ended. This method can be used to search file content, for example, in web scraping.
NB! Make sure that the text files (.txt) are in the same folder as your Python code. Otherwise, Python will not find the files.
Shoe size
The file footlengths.txt contains data about foot lengths. The following program reads the data from the file, calculates the suitable shoe size for each foot length, and prints the result. If the foot length cannot be converted into a number for some reason, then the program prints "Invalid input" and proceeds to the next line in the file.
def shoe_size(length): return round(1.5 * length + 2) ffile = open("footlengths.txt") for foot in ffile: try: f = float(foot) s = shoe_size(f) print("Foot length:", f, "Suitable shoe size is", s) except: print("Invalid input") ffile.close()
The try and except statements here are needed for converting the line into a number. If the conversion produces an error, then the message "Invalid input" is printed, and the loop continues with the next line of the file.
Exercises
1. Password
The following flowchart shows an algorithm for a web page registration form. Write a program that implements the process described in the flowchart.
Reversing the password means writing it backwards: drowssap.
Example
Enter username: Username
Enter password: Password
Enter password again: Password
The password must contain both letters and numbers! Try again.
Enter password: Password2
Enter password again: Password2
The password is 2drowssaP
Make sure that the program corresponds exactly to the flowchart: the program must first ask the user for three inputs, as shown in the flowchart, even if in some cases the error in the password can be detected already after entering the password for the first time. After informing the user about the mistake, the program needs to prompt only for the password (twice).
2. Sale
A shop sells different kinds of products. The shop owner has written the prices of all products in the file prices.txt. For example, bananas cost 1 euro per kilogram, tomatoes cost 3 euros, etc. The file has two lines for each product: product name on one line and its price on the following line. For example, the content of the file may be:
bananas 1 tomatoes 3 avocados three walnuts 18-19 yellow plums 4.5
For a sale, the shop owner wants to lower all prices by 10%. Write a program that reads the products and prices from the file, computes the new prices, if possible, and prints them on the screen, rounded to two decimal places.
The output should contain one line for each product. If price conversion is successful, then the line contains the name of the product and its new price. If price conversion is not successful, then the program should inform the user that the price for that product couldn't be computed.
New price for bananas is 0.9 euros.
New price for tomatoes is 2.7 euros.
Cannot convert the price for avocados.
Cannot convert the price for walnuts.
New price for yellow plums is 4.05 euros.
Autotester. The program doesn't prompt the user for anything, the data will always be read from the text file prices.txt. In the output, the data for each product must be on a separate line.
3. Taxi prices
The party ended and everybody starts to go home. The file taxiprices.txt contains information about taxi prices, where each line consists of taxi name, kilometer price, and starting fee, separated by commas. The program should ask for distance to home in kilometers and output the name of the cheapest taxi, according to the prices in the taxi price file.
Example
Content of the file taxiprices.txt:
Maxitaxi,0.6,2.0 Friendshare,0,10 Waldo takso,1.0,1.0
The output of the program:
Enter distance in kilometers: 7 Maxitaxi is the cheapest.
Taxi fare is computed by the formula kilometer price × distance in kilometers + starting fee.
The program should not ask for a filename. It can assume that the file taxiprices.txt exists.
Hint
>>> s = 'xx,yy,zz'.split(',') >>> s ['xx', 'yy', 'zz'] >>> s[1] 'yy'
Submit your solutions
Submit your solutions of exercises 1, 2 and 3 in Moodle under the names home1.py and home2.py, respectively.
Advice
Pay attention to code clarity. Programs are written for people to read and only incidentally for computers to execute.