Cairo University
Faculty of Graduate Studies for Statistical Research
Department of Computer and Information Sciences
Computer Sys. And Programming
Lec. 6 outline: You’ll find all the information you need here on
Sequences: Strings, String Assignment, Concatenation, and
Comparisons, Data Encryption, Data Decryption, Files, os Functions
, ….and ….
Tarek Aly
01126182476
http://41.32.221.109:8080/DrTarekAly.htm
E-mail: tarekmmmmt@{pg.cu.edu.eg; egyptpost.org; gmail.com; yahoo.com}
Contents
Sequences: Strings
String Assignment, Concatenation, and Comparisons
Positions or Indexes
Traversing with a for Loop
The Subscript Operator
Oddball Indexes
Slicing Strings
String Methods
The Basic ASCII Character Set
Data Encryption
Data Decryption
Files
Text Files
File Input
File Output
Managing Directories
os Functions
10/2/2023 Computer Sys. And Programming
Sequences
Sequences are collections of data values that are
ordered by position
A string is a sequence of characters
A list is a sequence of any Python data values
A tuple is like a list but cannot be modified
Examples
a = 'apple'
b = 'banana'
print(a, b) # Displays apple banana
fruits = (a, b) # A tuple
print(fruits) # Displays ('apple', 'banana')
veggies = ['bean', 'lettuce'] # A list
print(veggies) # Displays ['bean', 'lettuce']
Strings contain characters
Tuples and lists can contain anything
String Assignment,
Concatenation, and Comparisons
a = 'apple'
b = 'banana'
print(a + b) # Displays applebanana
print(a == b) # Displays False
print(a < b) # Displays True
Strings can be ordered like they are in a dictionary
Positions or Indexes
'Hi there!' H i t h e r e !
0 1 2 3 4 5 6 7 8
Each character in a string has a unique position called its index
We count indexes from 0 to the length of the string minus 1
A for loop automatically visits each character in the string,
from beginning to end
for ch in 'Hi there!': print(ch)
Traversing with a for Loop
'Hi there!' H i t h e r e !
0 1 2 3 4 5 6 7 8
A for loop automatically visits each character in the string,
from beginning to end
for ch in 'Hi there!': print(ch, end = '')
# Prints Hi there!
Summing with Strings
'Hi there!' H i t h e r e !
0 1 2 3 4 5 6 7 8
Start with an empty string and add characters to it with +
noVowels = ''
for ch in 'Hi there!':
if not ch in ('a', 'e', 'i', 'o', 'u',
'A', 'E', 'I', 'O', 'U'):
noVowels += ch
print(noVowels)
# Prints H thr!
The Subscript Operator
'Hi there!' H i t h e r e !
0 1 2 3 4 5 6 7 8
Alternatively, any character can be accessed using the subscript
operator []
This operator expects an int from 0 to the length of the string
minus 1
Example: 'Hi there!'[0] # equals 'H'
Syntax: <a string>[<an int>]
The len Function
'Hi there!' H i t h e r e !
0 1 2 3 4 5 6 7 8
The len function returns the
length of any sequence
>>> len('Hi there!')
9
>>> s = 'Hi there!'
>>> s[len(s) - 1]
'!'
An Index-Based Loop
'Hi there!' H i t h e r e !
0 1 2 3 4 5 6 7 8
If you need the positions during a loop, use the subscript
operator
s = 'Hi there!'
for ch in s: print(ch)
for i in range(len(s)): print(i, s[i])
Oddball Indexes
'Hi there!' H i t h e r e !
0 1 2 3 4 5 6 7 8
To get to the last character in a string:
s = 'Hi there!'
print(s[len(s) - 1]) # Displays !
Oddball Indexes
'Hi there!' H i t h e r e !
0 1 2 3 4 5 6 7 8
To get to the last character in a string:
s = 'Hi there!'
A negative index counts
print(s[len(s) - 1]) backward from the last position
# or, believe it or not, in a sequence
print(s[-1])
Slicing Strings
Extract a portion of a string (a substring)
s = 'Hi there!'
print(s[0:]) # Displays Hi there!
print(s[1:]) # Displays i there!
print(s[:2]) # Displays Hi (two characters)
print(s[0:2]) # Displays Hi (two characters)
The number to the right of : equals one plus the
index of the last character in the substring
String Methods
s = 'Hi there!'
print(s.find('there')) # Displays 3
print(s.upper()) # Displays HI THERE!
print(s.replace('e', 'a')) # Displays Hi thara!
print(s.split()) # Displays ['Hi', 'there!']
A method is like a function, but the syntax for its use is
different:
<a string>.<method name>(<any arguments>)
String Methods
s = 'Hi there!'
print(s.split()) # Displays ['Hi', 'there!']
A sequence of items in [ ] is a Python list
Characters in Computer
Memory
Each character translates to a unique
integer called its ASCII value (American
Standard for Information Interchange)
Basic ASCII ranges from 0 to 127, for 128
keyboard characters and some control
keys
The Basic ASCII Character Set
0 1 2 3 4 5 6 7 8 9
0 NUL SOH STX ETX EOT ENQ ACK BEL BS HT
1 LF VT FF CR SO SI DLE DC1 DC2 DC3
2 DC4 NAK SYN ETB CAN EM SUB ESC FS GS
3 RS US SP ! " # $ % & `
4 ( ) * + , - . / 0 1
5 2 3 4 5 6 7 8 9 : ;
6 < = > ? @ A B C D E
7 F G H I J K L M N O
8 P Q R S T U V W X Y
9 Z [ \ ] ^ _ ' a b c
10 d e f g h i j k l m
11 n o p q r s t u v w
12 x y z { | } ~ DEL
The ord and chr Functions
ord converts a single-character string to its ASCII value
chr converts an ASCII value to a single-character string
print(ord('A')) # Displays 65
print(chr(65)) # Displays A
for ascii in range(128): # Display 'em all
print(ascii, chr(ascii))
Data Encryption
A really simple (and quite lame) encryption algorithm
replaces each character with its ASCII value and a space
source = "I won't be here!"
code = ""
for ch in source:
code = code + str(ord(ch)) + " "
print(code)
# Displays 73 32 119 111 110 39 116 32 98 101 32 104 101 33
Data Decryption
To decrypt an encoded message, we split it into a list of
substrings and convert these ASCII values to the original
characters
source = ""
for ascii in code.split():
source = source + chr(int(ascii))
print(source) # Displays I won't be here!
Files
Data Storage
Data (and programs) are loaded into
primary memory (RAM) for
processing
From where?
From input devices (keyboard,
microphone)
From secondary memory - a hard disk, a
flash stick, a CD, or a DVD
Primary and Secondary Storage
Integrated Hard disk
circuits on CD
wafer-thin DVD
chips Flash
Primary Processor Secondary
Memory (RAM) memory
Very fast Slower
Expensive I/O devices Cheaper
Transient Keyboard Permanent
Mouse
Microphone
Monitor
Speakers
What Is a File?
A file is a software object that allows a
program to represent and access data
stored in secondary memory
Two basic types of files:
Text files: for storing and accessing text
(characters)
Binary files: executable programs and their
data files (such as images, sound clips, video)
Text Files
A text file is logically a sequence of
characters
Basic operations are
input (read characters from the file)
output (write characters to the file)
There are several flavors of each type of
operation
File Input
We want to bring text in from a file for
processing
Three steps:
Open the file for input
Read the text and save it in a variable
Process the text
Opening a File
<a variable> = open(<a file name>, <a flag>)
<a flag> can be
'r' - used for input, to read from an existing file
'w' - used for output, to overwrite an existing file
'a' - used for output, to append to an existing file
Example: Read Text from a File
filename = input('Enter a file name: ')
myfile = open(filename, 'r')
text = myfile.read()
print(text)
The file name must either be in the current directory or
be a pathname to a file in a directory
Python raises an error if the file is not found
text refers to one big string
Read Lines of Text from a File
filename = input('Enter a file name: ')
myfile = open(filename, 'r')
for line in myfile:
print(line)
The variable line picks up the next line of text on
each pass through the loop
line will contain the newline character, so the echo
will print extra blank lines
Read Lines of Text from a File
filename = input('Enter a file name: ')
myfile = open(filename, 'r')
for line in myfile:
print(line[:-1])
Extract a substring up to but not including the last
character (the newline)
This will produce an exact echo of the input file
Alternatively, Use readline
filename = input('Enter a file name: ')
myfile = open(filename, 'r')
while True:
line = myfile.readline()
if line == '':
break
print(line[:-1])
The readline method reads a line of text and
returns it as a string, including the newline character
This method returns the empty string if the end of file
is encountered
Count the Words
filename = input('Enter a file name: ')
myfile = open(filename, 'r')
wordcount = 0
for line in myfile:
wordcount += len(line.split())
print('The word count is', wordcount)
File Output
We want to save data to a text file
Four steps:
Open the file for output
Covert the data to strings, if necessary
Write the strings to the file
Close the file
Example: Write Text to a File
filename = input('Enter a file name: ')
myfile = open(filename, 'w')
myfile.write('Two lines\nof text')
myfile.close()
If the file already exists, it is overwritten; otherwise, it
is created in the current directory or path
The write method expects a string as an argument
Failure to close the file can result in losing data
Example: Write Integers to a File
filename = input('Enter a file name: ')
myfile = open(filename, 'w')
for i in range(1, 11):
myfile.write(str(i) + '\n')
myfile.close()
write can be called 0 or more times
Data values must be converted to strings before output
Separators, such as newlines or spaces, must be explicitly
written as well
Managing Directories
Directories are organized in a tree-like structure
Python’s os module includes many functions for
navigating through a directory system and managing it
D
D F F F D F
F F F D F
F F
os Functions
Function What It Does
os.getcwd() Returns the current working directory (string)
os.chdir(path) Attaches to the directory specified by path
os.listdir(path) Returns a list of the directory’s contents
os.remove(name) Removes a file at path
os.rename(old, new) Resets the old path to the new one
os.removedirs(path) Removes the directory (and all subdirectories)
at path
os.path Functions
Function What It Does
os.path.exists(path) Returns True if path exists or False
otherwise.
os.path.isdir(path) Returns True if path names a directory or
False otherwise.
os.path.isfile(path) Returns True if path names a file or
False otherwise.
os.path.getsize(path) Returns the size of the object named by
path in bytes.
Example: Does the File Exist?
import os.path
filename = input('Enter a file name: ')
if not os.path.exists(filename):
print('Error: the file not not exist!')
else:
myfile = open(filename, 'r')
print(myfile.read())
myfile.close()
Thank You
Let's get started!
2023-12-06 Computer Sys. And Programming