Chapter 5: Strings and Text Files

Chapter 5: Strings and Text Files

Strings

  • Data structure: consists of smaller pieces of data
  • String’s length: no. of characters (including spaces) it contains
  • >>> len(“”)
    0

Subscript operator

  • <a string>[<an integer operation>]
  • Index is usually in range (0,len); can be negative
# examine last character in string “name”
name[len(name) - 1]
# OR
name[-1]
  • Useful when you want to use the positions & characters in a string
  • E.g. count-controlled loop
data = “Hi there!”
for index in range(len(data)):
print(index, data[index])
OUTPUT:
0 H
1 i
2
3 t
4 h
5 e
6 r
7 e
8 !

Slicing for substrings (:)

  • [start:end+1] in terms of indices
>>> name = “myfile.txt”
>>> name[0:]                      # entire string
‘myfile.txt’
>>> name[:len(name)]        # entire string (because from index 0 to index len(name)-1)
‘myfile.txt’
>>> name[0:1]                    # first character
‘m’
>>> name[0:2]                    # first 2 characters
‘my’
>>> name[-3:]                    # last 3 characters
‘txt’
Note:
s[2:6]: s[2] to s[5]
s[:6]: first character to s[5]
s[2:]: s[2] to last character
s[::-1]: reverse string (full string but -1 stride)

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 each string, False otherwise
fileList = [“myfile.txt”, “myprogram.exe”, “yourfile.txt”]
for fileName in fileList:
if “.txt” in fileName:
print(fileName)
OUTPUT:
myfile.txt
yourfile.txt

String methods12

  • Behaves like a function, but has a slightly diff syntax
  • A method is always called with an object (a given data value)
  • <an object>.<method name>(<argument-1, …, <argument-n>)
  • 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 objects
  • Using example: >>> s = “Hi there!”
s.center(width)Returns a copy of s centred within the given number of columns
>>> s.center(11)
OUTPUT: ‘ Hi there! ’
s.count(sub [, start [, end]]3)Returns the no. of non-overlapping occurrences of substring sub in s. Optional arguments start and end are interpreted as in slice notation.
>>> s.count(‘e’)
OUTPUT: 2
s.endswith(sub)Returns True if s ends with sub or False otherwise
s.startswith(sub)Returns True if s starts with sub or False otherwise
s.find(sub [, start [, end]])Returns lowest index in s where substring sub is found. 4Optional arguments start and end are interpreted as in slice notation.
>>> s.find(‘the’)
OUTPUT: 3
s.isalpha()Returns True if s contains only letter or False otherwise
>>> ‘abc’.isalpha()
OUTPUT: True
s.isdigit()Returns True if s contains only digits or False otherwise
>>> “326”.isdigit()
OUTPUT: True
s.split([sep])Returns a list of the words in s, using sep as the delimiter string. If sep not specified, any whitespace string is a separator
>>> words = s.split()
>>> words
[‘Hi’, ‘there!’]
a.join(sequence)Returns a string that is the concatenation of the strings in the sequence. The separator between elements is s.
>>> “”.join(words)
‘Hithere!’
>>> “ ”.join(words)
‘Hi there!’
s.lower() / s.upper()Returns a copy of s converted to lowercase/uppercase
s.islower() / s.isupper()Return True is s is lowercase / uppercase or False otherwise
s.replace(old, new [, count])Returns a copy of s with all occurrences of substring old replaced by new. If the optional argument count is given, only the first count occurrences are replaced.
>>> s.replace(‘i’, ‘o’)
‘Ho there!’
s.strip([aString])Returns a copy of s with leading and trailing whitespace (tabs, space, newlines) removed. If aString is given, remove characters in aString instead
>>> “ Hi there! ”.strip()
‘Hi there!’

E.g.

s = "hello s6c students \n"
print(s.split())
print(s.strip()+'end')
print(s)
OUTPUT:
['hello', 's6c', 'students']
hello s6c studentsend
hello s6c students

E.g. counting no. of words and average word length

>>> sentence = input(“Enter a sentence: ”)
Enter a sentence: *This sentence has no long words*.
>>> listOfWords = sentence.split()
>>> print(“There are ”, len(listOfWords), “ words.”)
There are 6 words.
>>> sum = 0
>>> for word in listOfWords:
sum += len(word)
>>> print(“The average word length is”, sum / len(listOfWords))
The average word length is 4.5

E.g. extracting a filename’s extension

>>> “myfile.txt”.split(“.”)
[‘myfile’, ‘txt’]
>>> filename.split(“.”)[-1]     # the subscript [-1] extracts the last element, can be used to write a general expression for obtaining any filename’s extension

A string is an immutable data structure

  • When we use any method, it does not change the string itself
  • E.g.
s = “sample”
s.upper()
print(s)
OUTPUT: sample
s = “sample”
s = s.upper()        # assignment
print(s)
OUTPUT: SAMPLE
  • Note: s = ‘hello’; s[1] = ‘S’ or s[1:5] = ‘test’ gives TypeError: ‘str’ object does not support item assignment
  • Use
s = “hello 25s6c students”
# change 25s6c to 25S6C
s = s[:8] +S6C+ s[11:]

Text file = a software object that stores data on permanent medium (e.g. disk or CD)

  • Advantages of taking input data from a file compared to keyboard input from human user
  • Dataset can be much larger
  • Data can be be input much more quickly and with less chance of error
  • Data can be used repeatedly with the same program or with different program
  • Can create, view, and save data in a text file using text editor (e.g. Notepad or TextEdit)
  • All data output to or input from a text must be strings
open(pathname, mode)Opens a file at the given pathname and returns a file object.
Mode can be ‘r’, ‘w’, ‘rw’ (read/write), or ‘a’ (append)5.
f.close()Closes an output file. Not needed for input file
E.g. f = open(“myfile.txt”, ‘w’)
f.write(“First line.\nSecond line.\n”)
f.close()
[Alternative (not recommended): A levels requires a comment that file is closed] to automatically close files:
with open(“myfile.txt”, ‘w’) as f:
f.write(“First line.\nSecond line.\n”)
# the file will close automatically.
f.write(aString)Outputs aString to a file
f.read()Inputs contents of a file and returns them as a single string.
Returns ‘ ’ if end of file is reached
f.readline()Inputs a line of text and returns it as a string, including the newline.
Returns ‘ ’ if end of file is reached

Writing Text to a File

  • Data can be output to a text file using a file object
  • To open a file for output:
f = open(“myfile.txt”, ‘w’)
  • If file does not exist, it is created in the same folder of the Python scripts
  • If file already exists, Python opens it
  • When data are written to the file and file is closed, data previously existing in the file are erased

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)
import random
f = open(“integers.txt”, ‘w’)
for count in range(500):
number = random.randint(1,500) # randint is inclusive of both end points (?)
f.write(str(number) + “\\n”)
f.close()

Reading Text from a File

  • Open a file for input in a manner similar to opening a file for output
  • If pathname is not accessible from current working directory, Python raises an error

for loop method

f = open(“myfile.txt”, ‘r’)
for line in f:                           # read each line
line  = line.strip()      # remove \n
print(line)

read method

f = open(“myfile.txt”, ‘r’)
>>> text = f.read()
>>> text
First line.\\nSecond line.
>>> print(text)
First line.
Second line.
>>> lines = text.split(“\\n”)            # split string by \\n
['First line.', 'Second line.']
>>> for line in lines:
line = line.strip()
print(line)
f.close()

readline method

f = open(“myfile.txt”, ‘w’)
f.write(“First line.\\nSecond line.\\n”)
f.write(‘234’) # convert integer / float to string before writing to text file
f.close()
f = open(“myfile.txt”, ‘r’)
line = f.readline().strip()                  # read only one line, and remove \n
while line != ‘’:
print(line)                             # print current line
line = f.readline().strip()       # read next line (?), and remove \n

readlines method

f = open(“myfile.txt”, ‘r’)
lines = f.readlines()        # create a list of lines
for line in lines:
line = line.strip() # remove \n
print(line)

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 = open(“Integers2.txt”, ‘r’)
sum = 0
for line in f:
wordlist  = line.split()
First line → ['10', '20']
Second line → ['40', '60']
for word in wordlist:
number = int(word)
sum += number
print(“The sum is ”, sum)
with open(“Integers1.txt”, ‘r’) as f:
sum = 0
for line in f:
line = line.strip()
number = int(line)
sum += number
# file is closed automatically (MUST WRITE for “with open() as f”)
print(“The sum is ”, sum)
with open(“Integers2.txt”, ‘r’) as f:
sum = 0
for line in f:
wordlist = line.split()
for word in wordlist:
number = int(word)
sum += number
# file is closed automatically (MUST WRITE for “with open() as f”)
print(“The sum is ”, sum)

OUTPUT for both: The sum is 130

CSV file reading and writing

  • CSV file = text file in which data is separated by commas
# to read operation on CSV file
import csv
f = open(“myfile.csv”, ‘w’, newline = ‘ ’)
obj = csv.writer(f)
obj.writerow([“Mobile”, “Redmi”, 1500])
obj.writerow([“TV”, “Samsung”, 2500])
f.close()
# to write operation on CSV file
import csv
f = open(“myfile.csv”, ‘r’, newline = ‘ ’)
obj = csv.reader(f)
for row in obj:
print row
OUTPUT:
[‘Mobile’, ‘Redmi’, 1500]
[‘TV’, ‘Samsung’, 2500]

Comments from the Word document

Comments from the Word document

Footnotes

  1. Comment by ANDREA TAN KAI XUAN HCI: how to use in pseudocodes

  2. Comment by ANDREA TAN KAI XUAN HCI: cannot

  3. Comment by ANDREA TAN KAI XUAN HCI: index of start and end+1?

  4. Comment by ANDREA TAN KAI XUAN HCI: what if not found

  5. Comment by ANDREA TAN KAI XUAN HCI: whats these for