Python Module 3
Python Module 3
MODULE 3
Syllabus
Manipulating Strings: Working with Strings, Useful String Methods, Project: Password
Locker, Project: Adding Bullets to Wiki Markup
Reading and Writing Files: Files and File Paths, The os.path Module, The File Reading/Writing
Process, Saving Variables with the shelve Module,Saving Variables with the print.format()
Function, Project: Generating Random Quiz Files, Project: Multiclipboard
• Because Python thinks the string ends after Alice, and the rest (s cat.') is invalid
Python code.
Solution:
• Double Quotes
• spam = “That is Alice's cat.” → if you need to use both single quotes and double
quotes in the string, you’ll need to use escape characters.
\t Tab
\\ Backslash
Example 2:
>>> print("Hello there!\nHow are you?\nI\'m doing fine.")
Output:
Hello there!
How are you?
I'm doing fine.
• Because this is a raw string, Python considers the backslash as part of the string and not
as the start of an escape character.
2
Introduction to Python Programming - 22PLC105B/205B
print('''Dear Alice,
Eve's cat has been arrested for catnapping, cat burglary, and extortion.
Sincerely, Bob''')
Output:
Dear Alice,
Eve's cat has been arrested for catnapping, cat burglary, and extortion.
Sincerely, Bob
Note:
Below print statement gives you same output as above (Execute and Check)
print('Dear Alice,\n\nEve\'s cat has been arrested for catnapping, cat burglary, and
extortion.\n\nSincerely,\nBob')
Example
' H e l l o w o r l d ! '
0 1 2 3 4 5 6 7 8 9 10 11
• The space and exclamation point are included in the character count, so 'Hello world!'
is 12 characters long, from H at index 0 to ! at index 11.
Examples:
>>> spam = 'Hello world!'
>>> spam[0]
'H'
>>> spam[4]
3
Introduction to Python Programming - 22PLC105B/205B
'o'
>>> spam[-1]
'!'
>>> spam[0:5]
'Hello‘
>>> spam[:5]
'Hello'
>>> spam[6:]
'world!'
Example 1:
>>> spam = 'Hello world!'
>>> spam = spam.upper()
>>> spam
'HELLO WORLD!'
>>> spam = spam.lower()
4
Introduction to Python Programming - 22PLC105B/205B
>>> spam
'hello world!'
Note:
• These methods do not change the string itself but return new string values.
• If you want to change the original string, you have to call upper() or lower() on the
string and then assign the new string to the variable where the original was stored.
• This is why you must use spam = spam.upper() to change the string in spam instead of
simply spam.upper().
Example 2:
print('How are you?')
feeling = input()
if feeling.lower() == 'great':
print('I feel great too.')
else:
OUTPUT:
Example 1:
>>> spam = 'Hello world!'
>>> spam.islower()
False
>>> spam.isupper()
False
>>> 'HELLO'.isupper()
True
5
Introduction to Python Programming - 22PLC105B/205B
>>> 'abc12345'.islower()
True
>>> '12345'.islower()
False
>>> '12345'.isupper()
False
Example 2:
>>> 'Hello'.upper()
'HELLO'
>>> 'Hello'.upper().lower()
'hello'
>>> 'Hello'.upper().lower().upper()
'HELLO'
>>> 'HELLO'.lower()
'hello'
>>> 'HELLO'.lower().islower()
True
>>> 'hello'.isalpha()
True
>>> 'hello123'.isalpha()
False
>>> 'hello123'.isalnum()
True
>>> 'hello'.isalnum()
6
Introduction to Python Programming - 22PLC105B/205B
True
>>> '123'.isdecimal()
True
>>> ' '.isspace()
True
>>> 'This Is Title Case'.istitle()
True
False
1.10 Program repeatedly asks users for their age and a password until
they provide valid input.
while True:
if age.isdecimal():
break
Output:
7
Introduction to Python Programming - 22PLC105B/205B
Example:
>>> ', '.join(['cats', 'rats', 'bats'])
'cats, rats, bats'
>>> ' '.join(['My', 'name', 'is', 'Simon'])
'My name is Simon'
>>> 'ABC'.join(['My', 'name', 'is', 'Simon'])
'MyABCnameABCisABCSimon'
8
Introduction to Python Programming - 22PLC105B/205B
Example: The split() method does the opposite: It’s called on a string value and returns
a list of strings.
>>> 'My name is Simon'.split()
['My', 'name', 'is', 'Simon']
>>> 'MyABCnameABCisABCSimon'.split('ABC')
['My', 'name', 'is', 'Simon']
>>> 'My name is Simon'.split('m')
['My na', 'e is Si', 'on']
NOTE:
'Hello'.rjust(10) says that we want to right-justify 'Hello' in a string of total length 10.
'Hello' is five characters, so five spaces will be added to its left, giving us a string of 10
characters with 'Hello' justified right.
Example 2:
>>> 'Hello'.rjust(20, '*')
'***************Hello'
>>> 'Hello'.ljust(20, '-')
'Hello -------------- '
>>> 'Hello'.center(20)
‘ Hello '
>>> 'Hello'.center(20, '=')
‘=======Hello========'
NOTE:
The center() string method works like ljust() and rjust() but centers the text rather than
justifying it to the left or right.
9
Introduction to Python Programming - 22PLC105B/205B
Program:
def print Picnic(items Dict, left Width, right Width):
print('PICNIC ITEMS'. center(left Width + right Width, '-
'))for k, v in items Dict. items():
print(k. ljust (left Width, '.') + str(v).r just (right Width))
picnic Items = {'sandwiches': 4, 'apples': 12, 'cups': 4, 'cookies': 8000}
print Picnic(picnic Items, 12, 5)
print Picnic(picnic Items, 20, 6)
OUTPUT:
---PICNIC ITEMS--
sandwiches.. 4
apples .........12
cups ........... 4
cookies ..... 8000
-------PICNIC ITEMS-------
sandwiches............... 4
apples .................. 12
cups .................... 4
cookies .............. 8000
Output:
>>> spam.strip()
'Hello World'
>>> spam.lstrip()
'Hello World '
>>> spam.rstrip()
10
Introduction to Python Programming - 22PLC105B/205B
• Passing strip() the argument 'ampS' will tell it to strip occurences of a, m, p, and capital
S from the ends of the string stored in spam.
• The order of the characters in the string passed to strip() does not matter: strip('ampS')
will do the same thing as strip('mapS') or strip('Spam').
>>> spam = 'SpamSpamBaconSpamEggsSpamSpam'
>>> spam.strip('ampS')
'BaconSpamEggs‘
• Passing strip() the argument 'ampS' will tell it to strip occurences of a, m, p, and capital
S from the ends of the string stored in spam
Example:
NOTE:
• Pyperclip does not come with Python.
• To install it, follow the directions for installing third-party modules in Appendix A.
• After installing the pyperclip module, enter the following into the interactive shell:
>>> import pyperclip
>>> pyperclip.copy('Hello world!')
>>> pyperclip.paste()
'Hello world!’
1.16 Project: Password locker
#! python3
# pw.py - An insecure password locker program.
PASSWORDS = {'email': 'F7minlBDDuvMJuxESSKHFhTxFtjVB6',
'blog': 'VmALvQyKAxiVH5G8v01if1MLZF3sdt',
'luggage': '12345'}
11
Introduction to Python Programming - 22PLC105B/205B
pyperclip.copy(PASSWORDS[account])
print('Password for ' + account + ' copied to clipboard.')
else:
print('There is no account named ' + account)
12
Introduction to Python Programming - 22PLC105B/205B
13
Introduction to Python Programming - 22PLC105B/205B
• The C:\ part of the path is the root folder, which contains all other folders.
• On Windows, the root folder is named C:\ and is also called the C: drive.
• On OS X and Linux, the root folder is / (Forward Slash).
2.1.1 Backslash on Windows and Forward Slash on OS X and Linux
• On Windows, paths are written using backslashes (\) as the separator between folder
names.
• OS X and Linux, however, use the forward slash (/) as their path separator.
• If you want your programs to work on all operating systems, you will have to write
your Python scripts to handle both cases.
2.1.2 OS. path. join()
• If the string values of individual file and folder names are passed in your path,
os.path.join() will return a string with a file path using the correct path separators.
Example:
>>> import os
>>> os.path.join('usr', 'bin', 'spam')
'usr\\bin\\spam'
Note:
• I’m running these interactive shell examples on Windows, so os.path .join('usr', 'bin',
'spam') returned 'usr\\bin\\spam'. (Notice that the backslashes are doubled because each
backslash needs to be escaped by another backslash character.)
• If I had called this function on OS X or Linux, the string would have been
'usr/bin/spam'.
Example 2:
>>> myFiles = ['accounts.txt', 'details.csv', 'invite.docx']
14
Introduction to Python Programming - 22PLC105B/205B
C:\Users\asweigart\invite.docx
• Every program that runs on your computer has a current working directory, or cwd.
• Any filenames or paths that do not begin with the root folder are assumed to be under
the current working directory.
• You can get the current working directory as a string value with the os.getcwd()
function and change it with os.chdir().
Example:
>>> import os
>>> os.getcwd() #function returns the current working directory as a string value
'C:\\Python34'
>>> os.chdir('C:\\Windows\\System32')
>>> os.getcwd()
'C:\\Windows\\System32'
Python will display an error if you try to change to a directory that does not exist.
>>> os.chdir('C:\\ThisFolderDoesNotExist')
Traceback (most recent call last):
File "<pyshell#18>", line 1, in <module>
os.chdir('C:\\ThisFolderDoesNotExist')
FileNotFoundError: [WinError 2] The system cannot find the file specified:
'C:\\ThisFolderDoesNotExist'
2.1.4 Absolute vs. Relative Paths
• There are two ways to specify a file path.
• An absolute path, which always begins with the root folder.
• A relative path, which is relative to the program’s current working directory
• There are also the dot (.) and dot-dot (..) folders. These are not real folders but special
names that can be used in a path. A single period (“dot”) for a folder name is shorthand
for “this directory.” Two periods (“dot-dot”) means “the parent folder.”
15
Introduction to Python Programming - 22PLC105B/205B
>>> import os
>>> os.makedirs('C:\\delicious\\walnut\\waffles')
• The os.path module contains many helpful functions related to filenames and file
paths.
Example 1:
This is an easy way to convert a relative path into an absolute one.
>>> os.path.abspath('.')
‘C:\\Users\\Anand\\AppData\\Local\\Programs\\Python\\Python39'
>>> os.path.isabs('.')
16
Introduction to Python Programming - 22PLC105B/205B
False
>>> os.path.isabs(os.path.abspath('.'))
True
Example 2:
Enter the following calls to os.path.relpath() into the interactive shell:
>>> os.path.relpath('C:\\Windows', 'C:\\')
'Windows'
Example 3:
>>> path = 'C:\\Windows\\System32\\calc.exe'
>>> os.path.basename(path)
'calc.exe'
>>> os.path.dirname(path)
'C:\\Windows\\System32‘
Example 4:
• dir name and base name together can be obtained by using os.path.split() to get a tuple
value with these two strings
>>>path1='C:\\Windows\\System32\\calc.exe'
>>>os.path.split(path1)
('C:\\Windows\\System32', 'calc.exe')
Hence os.path.split() is a nice shortcut if you need both values.
Example 5:
• use the split() string method and split on the string in os.sep.
>>> import os
>>> path1='C:\\Windows\\System32\\calc.exe'
>>> path1.split(os.path.sep)
17
Introduction to Python Programming - 22PLC105B/205B
• Calling os.path.getsize(path) will return the size in bytes of the file in the path
argument.
• Calling os.listdir(path) will return a list of filename strings for each file in the path
argument.
Output:
>>>os.path.getsize('C:\\Windows\\System32\\calc.exe')
18
Introduction to Python Programming - 22PLC105B/205B
>>> helloContent
Writing to Files
Example 1:
>>>baconFile = open(r'E:\SAMPLE\HI.txt', 'w')
>>> baconFile.write('Hello world!\n')
13 # returns the number of characters written
>>> baconFile.close()
>>> baconFile = open(r'E:\SAMPLE\HELLO.txt', 'w')
>>> baconFile.write('Hello BHASKARA STUDENTS!\n')
25
>>> baconFile.close()
Example 2:
>>> baconFile = open('bacon.txt', 'a')
>>> baconFile.write('Bacon is not a vegetable.')
25
>>> baconFile.close()
>>> baconFile = open('bacon.txt')
>>> content = baconFile.read()
>>> baconFile.close()
>>> print(content)
Hello world!
Bacon is not a vegetable.
19
Introduction to Python Programming - 22PLC105B/205B
Example:
>>> import shelve
>>> shelfFile = shelve.open('mydata')
>>> shelfFile.close()
• To read and write data using the shelve module, you first import shelve.
• Call shelve.open() and pass it a filename, and then store the returned shelf value in a
variable.
• You can make changes to the shelf value as if it were a dictionary.
• After running the previous code on Windows, you will see three new files in the current
working directory: mydata.bak, mydata.dat, and mydata.dir
Example:
>>> import pprint
>>> cats = [{'name': 'Zophie', 'desc': 'chubby'}, {'name': 'Pooka', 'desc': 'fluffy'}]
>>> pprint.pformat(cats)
"[{'desc': 'chubby', 'name': 'Zophie'}, {'desc': 'fluffy', 'name': 'Pooka'}]"
>>> fileObj = open('myCats.py', 'w')
>>> fileObj.write('cats = ' + pprint.pformat(cats) + '\n')
83
>>> fileObj.close()
20
Introduction to Python Programming - 22PLC105B/205B
Programming Solution:
Step 1: Store the Quiz Data in a Dictionary
#! python3
*1 import random
# The quiz data. Keys are states and values are their capitals.
21
Introduction to Python Programming - 22PLC105B/205B
Step 2: Create the Quiz File and Shuffle the Question Order
#! python3
--snip—
22
Introduction to Python Programming - 22PLC105B/205B
*3quizFile.write('Name:\n\nDate:\n\nPeriod:\n\n')
quizFile.write((' ' * 20) + 'State Capitals Quiz (Form %s)' % (quizNum + 1))
quizFile.write('\n\n')
states = list(capitals.keys())
*4random.shuffle(states)
• The filenames for the quizzes will be capitalsquiz.txt, where is a unique number for the quiz that
comes from quizNum, the for loop’s counter.
• The answer key for capitalsquiz.txt will be stored in a text file named capitalsquiz_answers.txt.
Each time through the loop, the %s placeholder in 'capitalsquiz%s.txt' and
'capitalsquiz_answers%s.txt' will be replaced by (quizNum + 1), so the first quiz and answer key
created will be capitalsquiz1.txt and capitalsquiz_answers1.txt. These files will be created with
calls to the open() function at *1 and *2, with 'w' as the second argument to open them in write
mode.
• *3 The write() statements at w create a quiz header for the student to fill out.
• *4 Finally, a randomized list of US states is created with the help of the random.shuffle() function
Step 3: Create the Answer Options
Now you need to generate the answer options for each question, which will be multiple choice
from A to D.
#! python3
--snip—
*1 correctAnswer = capitals[states[questionNum]]
23
Introduction to Python Programming - 22PLC105B/205B
*2 wrongAnswers = list(capitals.values())
*3 del wrongAnswers[wrongAnswers.index(correctAnswer)]
*4 wrongAnswers = random.sample(wrongAnswers, 3)
*6 random.shuffle(answerOptions)
# TODO: Write the question and answer options to the quiz file.
*1 The correct answer is easy to get—it’s stored as a value in the capitals dictionary
*2 The list of possible wrong answers is trickier. You can get it by duplicating all the values in the
capitals dictionary
*5 The full list of answer options is the combination of these three wrong answers with the correct
answers
24
Introduction to Python Programming - 22PLC105B/205B
25