HCI 6. Strings and Text Files (2022) revised
Uploaded by adrianwang2003 · 28 May 2024
Preview
Text from the first pagesHwa Chong Institution H2 Computing 1 6 Strings and Text Files Learning Outcome 6.1 Accessing Characters and Substrings in Strings 6.1.1 The Structure of Strings ● Data structure: Consists of smaller pieces of data ● String’s length: Number of characters it contains (0+) 6.1.2 The Subscript Operator The form of the subscript operator is: Subscript operator is useful when you want to use the positions as well as the characters in a string. For example, we can use a count-controlled loop below. Programming Elements and Consturcts Understand the data type string and use common library functions for strings Implementing Algorithms and Data Structures Store data in and retrieve data from serial and sequential text files
Hwa Chong Institution H2 Computing 2 6.1.3 Slicing for Substrings Python’s subscript operator can be used to obtain a substring through a process called slicing. Place a colon (:) in the subscript; an integer value can appear on either side of the colon. 6.1.4 Testing for a Substring with the in Operator When used with strings, the left operand of in is a target substring and the right operand is the string to be searched. Returns True if target string is somewhere in search string, or False otherwise.
Hwa Chong Institution H2 Computing 3 6.2 String Methods Python includes a set of string operations called methods that make tasks like counting the words in a single sentence easy. A method behaves like a function, but has a slightly different syntax. A method is always called with a given data value called an object. ● Methods can expect arguments and return values ● A method knows about the internal state of the object with which it is called ● In Python, all data values are in fact objects
Hwa Chong Institution H2 Computing 4
Hwa Chong Institution H2 Computing 5 Example: counting number of words Example: extracting a filename’s extension The subscript [ -1] extracts the last element. It can be used to write a general expression for obtaining any filename’s extension, as follows: A string is an immutable data structure . When we use any method, it does not change the string itself. Note the difference of the following two sets of code.
Hwa Chong Institution H2 Computing 6 6.3 Text Files A text file is software object that stores data on permanent medium such as disk or CD. When compared to keyboard input from human user, the main advantages of taking input data from a file are: ● The data set can be much larger ● The data can be input much more quickly and with less chance of error ● The data can be used repeatedly with the same program or with different programs 6.3.1 Text Files and Their Format Using a text editor such as Notepad or TextEdit, you can create, view, and save data in a text file. All data output to or input from a text file must be strings. 6.3.2 Writing Text to a File Data can be output to a text file using a file object. To open a file for output: If file does not exist, it is created in the same folder of the Python scripts. If it already exists, Python opens it; when data are written to the file and the file is closed, any data previously existing in the file are erased. Alternatively, we can use the following Python codes where the file is automatically closed. (Not recommended. A-level requires a comment that file is closed.) with open("myfile.txt", 'w') as f: f.write("First line.\nSecond line.\n") # the file will close automatically.
Hwa Chong Institution H2 Computing 7 6.3.3 Writing Numbers to a File The file method write expects a string as an argument. Other types of data must first be converted to strings before being written to output file (e.g., using str). 6.3.4 Reading Text from a File You open a file for input in a manner similar to opening a file for output. If the pathname is not accessible from the current working directory, Python raises an error. ● the read method ● the readline method
Hwa Chong Institution H2 Computing 8 6.3.5 Reading Numbers from a File Text file “Integers1.txt” 10 20 40 60 Text file “Integers2.txt” 10 20 40 60 f = open("Integers1.txt",'r') sum = 0 for line in f: line = line.strip() number = int(line) sum += number print("The sum is ",sum) f.close() f = open("Integers2.txt",'r') sum = 0 for line in f: wordlist = line.split() for word in wordlist: number = int(word) sum += number print("The sum is ",sum) f.close() with open("Integers1.txt", 'r') as f: sum = 0 for line in f: line = line.strip() number = int(line) sum += number print("The sum is ",sum) with open("Integers1.txt", 'r') as f: sum = 0 for line in f: wordlist = line.split() for word in wordlist: number = int(word) sum += number print("The sum is ",sum) Notice the different ways of reading numbers based on the format of the text file. The outcome for both codes is The sum is 130
Hwa Chong Institution H2 Computing 9 Tutorial 6 1. Write in pseudocode, an algorithm to accomplish the following: (a) Replaces s1 with s2. (b) Appends s2 to s1. 2. Assume that the variable data refers to the string “myprogram.exe”. Write the values of the following expressions: (a) data[2] (b) data[-1] (c) len(data) (d) data[0:8] 3. Assume that the variable data refers to the string “myprogram.exe”. Write the expression that perform the following tasks: (a) Extract the substring “gram” from data. (b) Truncate the extension “.exe” from data. (c) Extract the character at the middle position from data. 4. Assume that the variable data refers to the string “Python rules!” . Use a string method to perform the following tasks: (a) Obtain a list of words in the string (b) Convert the string to uppercase (c) Locate the position of the string “rules”. (d) Replace the exclamation point with a question mark. 5. Assume that the variable data refers to the string “Python rules!” . Write the values of the following expressions: (a) data.endswith(‘i’) (b) “ totally “.join(data.split()) 6. Write a code segment that opens a file named myfile.txt for input and prints the number of lines in the file.
Hwa Chong Institution H2 Computing 10 7. Assume that a file named word.txt contains words separated by newlines. Write a code segment that opens a file for input and prints the number of four-letter words in the file. 8. Assume that a file named integer.txt contains integers separated by newlines. Write a code segment that opens the file and prints the average value of the integers. 9. How many different codes can you think about to read a text file? Assignment 6 1. Assume that the variable myString refers to a string. Write a code segment that uses a loop to print the characters of the string in reverse order. 2. Write a function that takes a binary number of up to 16 digits, and converts it into a hexadecimal number. 3. Write a script named copyfile.py. This script should prompt the user for the names of two text files. The contents of the first file should be input and written to the second file. You may use the text files in Tutorial 6 question 6 and 7 for testing purpose. 4. The Payroll Department keeps a list of employee information for each pay period in a text file. The format of each line of the file is the following: <last name> <hourly wage> <hours worked> Write a program that reads data from the file Payroll.txt and prints to the terminal a report of the wages paid to the employees for the given period. The report should be in tabular format with the appropriate header. Each line should contain an employee’s name, th
Content continues in the PDF. Download PDF
Related notes
- NYJC 2026 Prelim P2Exam Papers · 2026
- NYJC 2026 Prelim P1Exam Papers · 2026
- DHS 2026 Y6 H2 Computing Prelim Paper 2_finalExam Papers · 2026
- ACJC 2026 JC2 Computing Prelim Paper 2 (Practical)Exam Papers · 2026
- 2026_NJC Prelim_Computing_P2.pdfExam Papers · 2026
- 2026_JPJC_Computing_Prelim_P2_finalExam Papers · 2026
- 2026_JPJC_Computing_Prelim_P1_markschemeExam Papers · 2026
- 2026_JPJC_Computing_Prelim_P1_finalExam Papers · 2026
- 2026 ACJC Prelim Computing Paper 2Exam Papers · 2026
- 2024 ACJC Computing PromoExam Papers · 2024
- 2023 ACJC Promo QPExam Papers · 2023
- 2022 ACJC Computing Promo Paper 2Exam Papers · 2022
- See all H2 Computing notes

