KEMBAR78
Module - 3 | PDF | Computer File | Directory (Computing)
0% found this document useful (0 votes)
11 views107 pages

Module - 3

This document covers string manipulation in Python, including concepts such as indexing, slicing, escape characters, and various string methods. It also introduces file handling, explaining file properties, paths, and the current working directory. Additionally, it presents projects like a password locker and a bullet point adder using the pyperclip module.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views107 pages

Module - 3

This document covers string manipulation in Python, including concepts such as indexing, slicing, escape characters, and various string methods. It also introduces file handling, explaining file properties, paths, and the current working directory. Additionally, it presents projects like a password locker and a bullet point adder using the pyperclip module.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 107

Module -3

Strings and File


handling
CHAPTER: MANIPULATING
STRINGS
Working with Strings,
Useful String Methods,
Project: Password Locker,
Project: Adding Bullets to Wiki Markup
Working with Strings
What is a String?
• String is a data type in Python
• It represents a sequence of characters enclosed within quotes.
Example :
>>>college = ‘Sai Vidya Institute of Technology’
>>>message = “Good morning”
Indexing
Index 0 1 2 3 4 5

String P Y T H O N

Negative -6 -5 -4 -3 -2 -1
Index

>>> name = ‘PYTHON’ >>> name = ‘PYTHON’


>>> name[0] >>> name[-1]
‘P’ ‘N’
>>>name[1] >>>name[-2]
‘Y’ ‘O’
>>>name[2] >>>name[-3]
‘T’ ‘H’
String Slicing
SLICING

>>> name = ‘PYTHON’ >>> name = ‘PYTHON’


>>> name[0 : 6] >>> name[-6 : -4 ]
‘PYTHON’ ‘PY’
>>>name[2 :] >>>name[-4 : ]
‘THON’ ‘THON’
>>>name[ : : 2] >>>name[ : : -1]
‘PTO’ ‘NOHTYP’
ESCAPE CHARACTERS
An escape character lets you use characters that are otherwise
impossible to put into a string. An escape character consists of a
backslash (\) followed by the character you want to add to the string

>>> spam = 'Say hi to Bob\'s mother.’


Table 1: Escape sequence
>>> print("Hello there!\nHow are you?\nI\'m doing
fine.")
Hello there!
How are you?
I'm doing fine.
Raw Strings
• A raw string completely ignores all escape characters and prints any
backslash that appears in the string.

• You can place an r before the beginning quotation mark of a string to


make it a raw string.

>>> print(r'That is Carol\'s cat.')


That is Carol\'s cat.

>>>print(r'c:\books\notes’)

c:\books\notes
Multiline Strings with Triple Quotes

• A multiline string in Python begins and ends with either three single
quotes or three double quotes.

• Any quotes, tabs, or newlines in between the “triple quotes” are


considered part of the string.

• Python’s indentation rules for blocks do not apply to lines inside a


multiline string.
>>>print('''Dear Alice,

Eve's cat has been arrested for catnapping, cat


burglary, and extortion.

Sincerely,
Bob''')

Dear Alice,

Eve's cat has been arrested for catnapping, cat


burglary, and extortion.

Sincerely,
Bob
Multiline Comments
• A multiline string is often used for comments that span multiple lines.

"""This is a test Python program.


Written by Al Sweigart al@inventwithpython.com
This program was designed for Python 3, not Python 2.
"""

def factorial():
"""This is a multiline comment to help
explain what the spam() function does."""

print(‘Factorial Program')
The in and not in operators with
Strings
Python “in” operator is used to check whether a
specified value is a constituent element of a
sequence like string, array, list, tuple, etc.
>>> ‘Sai’ in ‘Sai Vidya’
True
>>> ‘good’ in ‘good morning’
True
>>> ‘blue’ not in ‘ sea blue’
False
>>>’101’ in ‘909000100’
False
USEFUL STRING METHODS
• upper() – returns a string of uppercase letters
• lower() – returns a string of lowercase letters
• isupper() - returns a Boolean True value if the string has
at least one letter and all the letters are
uppercase.
Otherwise, returns False
• islower() - returns a Boolean True value if the string has
at least one letter and all the letters are
lowercase.
Otherwise, returns False
>>> spam = 'Hello, world!'
>>> spam = spam.upper()
>>> spam
'HELLO, WORLD!'
>>> spam = spam.lower()
>>> spam
'hello, world!'
print('How are you?')
feeling = input()
if feeling.lower() == 'great':
print('I feel great too.')
else:
print('I hope the rest of your day is good.')

Output:
How are you?
GREat
I feel great too.
>>> spam = 'Hello, world!'
>>> spam.islower()
False
>>> spam.isupper()
False
>>> 'HELLO'.isupper()
True
>>> 'abc12345'.islower()
True
>>> '12345'.islower()
False
>>> '12345'.isupper()
False
The isX() Methods
• isalpha() Returns True if the string consists only of letters and isn’t
blank

• isalnum() Returns True if the string consists only of letters and numbers
and is not blank

• isdecimal() Returns True if the string consists only of numeric


characters and is not blank

• isspace() Returns True if the string consists only of spaces, tabs, and
newlines and is not blank

• istitle() Returns True if the string consists only of words that begin
with an uppercase letter followed by only lowercase letters
>>> 'hello'.isalpha() >>> 'This Is Title Case'.istitle()

True True
>>> 'This Is Title Case 123'.istitle()
>>> 'hello123'.isalpha()
True
False
>>> 'This Is not Title Case'.istitle()
>>> 'hello123'.isalnum() False
True >>> 'This Is NOT Title Case
Either'.istitle()
>>> 'hello'.isalnum()
False
True

>>> '123'.isdecimal()

True

>>> ' '.isspace()

True
while True:
print('Enter your age:')
age = input()
if age.isdecimal():
break
print('Please enter a number for your age.')

while True:
print('Select a new password (letters and numbers only):')
password = input()
if password.isalnum():
break
print('Passwords can only have letters and numbers.')
The startswith() and endswith()
Methods
>>> 'Hello, world!'.startswith('Hello')
True
>>> 'Hello, world!'.endswith('world!')
True
>>> 'abc123'.startswith('abcdef')
False
>>> 'abc123'.endswith('12')
False
>>> 'Hello, world!'.startswith('Hello, world!')
True
>>> 'Hello, world!'.endswith('Hello, world!')
The join()

• The join() method is useful when you have a list of strings


that need to be joined together into a single string value.

• The join() method is called on a string, gets passed a list of


strings, and returns a string.
>>> ' '.join(['My', 'name', 'is', 'Simon'])
'My name is Simon'
>>> 'ABC'.join(['My', 'name', 'is', 'Simon'])
'MyABCnameABCisABCSimon’

>>> ', '.join(['cats', 'rats', 'bats'])


'cats, rats, bats'
split() Methods
• The split() method is called on a string value and
returns a list of strings.
• By default, the string is split wherever whitespace
characters such as the space, tab, or newline characters
are found.
• You can pass a delimiter string to the split() method
to specify a different string to split upon.
>>> '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']
>>> spam = '''Dear Alice,
How have you been? I am fine.
There is a container in the fridge
that is labeled "Milk Experiment."

Please do not drink it.


Sincerely,
Bob'''
>>> spam.split('\n')
['Dear Alice,', 'How have you been? I am fine.', 'There is a
container in the fridge', 'that is labeled "Milk Experiment."',
'', 'Please do not drink it.',
'Sincerely,', 'Bob']
Splitting Strings with the partition()
Method
• The partition() string method can split a string into the text

before and after a separator string.

• This method searches the string it is called on for the separator

string it is passed, and returns a tuple of three substrings for

the “before,” “separator,” and “after” substrings.


>>> 'Hello, world!'.partition('w')
('Hello, ', 'w', 'orld!')
>>> 'Hello, world!'.partition('world')
('Hello, ', 'world', '!')
Justifying Text with the rjust(),
ljust(), and center() Methods
• The rjust() and ljust() string methods return a padded
version of the string they are called on, with spaces
inserted to justify the text.

• The first argument to both methods is an integer length


for the justified string.
>>> 'Hello'.rjust(10)
' Hello'
>>> 'Hello'.rjust(20)
' Hello'
>>> 'Hello, World'.rjust(20)
' Hello, World'
>>> 'Hello'.ljust(10)
'Hello '
>>> 'Hello'.rjust(20, '*')
'***************Hello'
>>> 'Hello'.ljust(20, '-')
'Hello---------------'

>>> 'Hello'.center(20)
' Hello '
>>> 'Hello'.center(20, '=')
'=======Hello========'
Removing Whitespace with the
strip(), rstrip(), and lstrip() Methods
• Sometimes you may want to strip off whitespace
characters (space, tab, and newline) from the left side,
right side, or both sides of a string.

• The strip() string method will return a new string without


any whitespace characters at the beginning or end.

• The lstrip() and rstrip() methods will remove whitespace


characters from the left and right ends, respectively.
>>> spam = ' Hello, World '
>>> spam.strip()
'Hello, World'
>>> spam.lstrip()
'Hello, World '
>>> spam.rstrip()
' Hello, World'
NUMERIC VALUES OF CHARACTERS
WITH THE ORD() AND CHR() FUNCTIONS
• Computers store information as bytes—strings of binary numbers, which
means we need to be able to convert text to numbers.

• Because of this, every text character has a corresponding numeric value


called a Unicode code point.

• For example, the numeric code point is 65 for 'A', 52 for '4', and 33 for '!’.

• ord() function can be used to get the code point of a one-character string,
and the chr() function can be used to get the one-character string of an
integer code point.
>>> ord('A') >>> ord('B')
65 66
>>> ord('4') >>> ord('A') < ord('B')
52 True
>>> ord('!') >>> chr(ord('A'))
33 'A'
>>> chr(65) >>> chr(ord('A') + 1)
'A' 'B'
COPYING AND PASTING STRINGS
WITH THE PYPERCLIP MODULE
• The pyperclip module has copy() and paste() functions that
can send text to and receive text from your computer’s clipboard.

• Sending the output of your program to the clipboard will make it


easy to paste it into an email, word processor, or some other
software.

Note: View the clipboard contents using windows + v key on the keyboard
>>> import pyperclip
>>> pyperclip.copy('Hello, world!')
>>> pyperclip.paste()
'Hello, world!'
>>> pyperclip.paste()
'For example, if I copied
this sentence to the
clipboard and then called
paste(), it would look like
this:'
PROJECT: ADDING BULLETS TO
WIKI MARKUP
The bulletPointAdder.py script will get the text from the
clipboard, add a star and space to the beginning of each
line, and then paste this new text to the clipboard.
After executing
bulletPointAdder.py script, the
Initial content on the clipboard
content on the clipboard
Lists of animals * Lists of animals
Lists of aquarium life * Lists of aquarium life
Lists of biologists * Lists of biologists
Lists of cultivars * Lists of cultivars
import pyperclip
text = pyperclip.paste()

# Separate lines and add stars.


lines = text.split('\n')

for i in range(len(lines)): # loop through all indexes for "lines" list

lines[i] = '* ' + lines[i] # add star to each string in "lines" list

text = '\n'.join(lines)
pyperclip.copy(text)
PROJECT: PASSWORD LOCKER

• You probably have accounts on many different websites.

• It’s a bad habit to use the same password for each of them because if any of
those sites has a security breach, the hackers will learn the password to all of
your other accounts.

• It’s best to use password manager software on your computer that uses one
master password to unlock the password manager.

• Then you can copy any account password to the clipboard and paste it into
the website’s Password field.
Password Locker Program
PASSWORDS = {'email': 'F7minlBDDuvMJuxESSKHFhTxFtjVB6’,

'blog': 'VmALvQyKAxiVH5G8v01if1MLZF3sdt’,

‘gmail': '12345’}

import sys, pyperclip

if len(sys.argv) < 2:

print('Usage: python pw.py [account] - copy account


password’)

sys.exit()
account = sys.argv[1] # first command line arg is the account name
if account in PASSWORDS:
pyperclip.copy(PASSWORDS[account])
print('Password for ' + account + ' copied to
clipboard.')
else:
print('There is no account named ' +account)
CHAPTER: 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
What is a File?

• Files are containers to hold data

• Variables are a fine way to store data while your


program is running, but if you want your data to persist
even after your program has finished, you need to save
it to a file.

• You can think of a file’s contents as a single string


value, potentially gigabytes in size.
FILES AND FILE PATHS
• A file has two key properties: a filename and a path.
• The path specifies the location of a file on the computer.
For example, there is a file with the
filename project.docx in the path C:\Users\Al\Documents.
• The part of the filename after the last period is called the
file’s extension that specifies a file’s type.
• The filename project.docx is a Word document,
and Users, Al, and Documents all refer to folders (also
called directories).
• Folders can contain files and other folders.
For example, project.docx is in the Documents folder,
which is inside the Al folder, which is inside the Users folder.
• File name: project.docx
• Path: C:\Users\Al\Documents
• File extension: docx
• Folder or directories:
Users, Al, Documents
• Root folder: C:\

Fig. 1: A file in a hierarchy of folders


The Current Working Directory
• Every program that runs on the 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.

>>> from pathlib import Path


>>> Path.cwd()
WindowsPath('C:/Users/Students/Akhil')
>>> import os
>>> os.chdir('C:\\Windows\\System32')
>>> Path.cwd()
WindowsPath('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 "<stdin>", line 1, in <module>
FileNotFoundError: [WinError 2] The system cannot
find the file specified:
'C:/ThisFolderDoesNotExist'
The Home Directory

• All users have a folder for their own files on the computer called
the home directory or home folder.

• You can get a Path object of the home folder by


calling Path.home():

>>>Path.home()

WindowsPath('C:/Users/Student')
• The home directories are located in a set place
depending on your operating system:

• On Windows, home directories are under C:\Users.

• On Mac, home directories are under /Users.

• On Linux, home directories are often under /home.


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 names used in
Path. A single period (“dot”) for a folder name is shorthand for
“this directory.” Two periods (“dot-dot”) means “the parent folder.”
Figure : The relative paths for folders and files in the working directory C:\bacon
Creating New Folders Using the os.makedirs()
Function
>>> import os
>>> os.makedirs('C:\\delicious\\walnut\\waffles’)

Figure : The result of os.makedirs('C:\\delicious\\walnut\\waffles')


To make a directory from a Path object, call
the mkdir() method. For example, this code will
create a spam folder under the home folder on my
computer:
>>> from pathlib import Path
>>> Path(r’C:\Python\module1\notes’).mkdir()
Handling Absolute and Relative Paths
is_absolute()method returns True only if the
Path Object is a absolute path

>>> Path.cwd()
WindowsPath('C:/Users/Students/Program’)

>>> Path.cwd().is_absolute()
True

>>> Path('spam/bacon/eggs').is_absolute()
False
To get an absolute path from a relative path, you can
put Path.cwd()/ in front of the relative Path object.

>>> Path('my/relative/path')
WindowsPath('my/relative/path’)

>>> Path.cwd() / Path('my/relative/path')


WindowsPath('C:/Users/Student/Programs/my/relative/path')
Using os.path
1. To convert a relative path into an absolute
path os.path.abspath(path)can be used. This function will
return a string of the absolute path of the argument.

2. os.path.isabs(path) will return True if the argument is an


absolute path and False if it is a relative path.

3. os.path.relpath(path, start) will return a string of a


relative path from the start path to path. If start is not
provided, the current working directory is used as the start
path.
>>> os.path.abspath('.')
'C:\\Users\\Student\\Programs’

>>> os.path.abspath('.\\Scripts')
'C:\\Users\\Student\\Programs\\Scripts’

>>> os.path.isabs('.')
False

>>> os.path.isabs(os.path.abspath('.'))
True
Getting the Parts of a File Path
Given a Path object, you can extract the file path’s different parts as strings
using several Path object attributes.

Figure: The parts of a Windows (top) and macOS/Linux (bottom)


file path
The parts of a file path include the following:

• The anchor, which is the root folder of the filesystem

• On Windows, the drive, which is the single letter that often


denotes a physical hard drive or other storage device

• The parent, which is the folder that contains the file

• The name of the file, made up of the stem (or base name)
and the suffix (or extension)
>>> p = Path('C:/Users/Student/spam.txt’)
>>> p.anchor
'C:\\’
>>> p.parent
WindowsPath('C:/Users/Student’)
>>> p.name
'spam.txt’
>>> p.stem
'spam’
>>> p.suffix
'.txt’
>>> p.drive
'C:'
Finding File Sizes and Folder
Contents
The os.path module provides functions for finding the
size of a file in bytes and the files and folders inside a
given folder.

• 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.
>>> os.path.getsize('C:\\Windows\\System32\\calc.exe')
27648

>>> os.listdir('C:\\Python')
[‘Module1', ‘Module2']
Modifying a List of Files Using Glob
Patterns
• Path objects have a glob() method for listing the
contents of a folder according to a glob pattern.

• Glob patterns are like a simplified form of regular


expressions often used in command line commands.

• The glob() method returns a generator object


>> p = Path(‘C:\\delicious’)

>>> p.glob('*')
<generator object Path.glob at 0x000002A6E389DED0>

>>> list(p.glob('*')) # Make a list from the generator.

[WindowsPath('c:/delicious/desserts'),

WindowsPath('c:/delicious/menu.docx'),

WindowsPath('c:/delicious/orders.txt'),

WindowsPath('c:/delicious/walnut’)]

>>> list(p.glob('*.txt') # Lists all text files.


[WindowsPath('c:/delicious/orders.txt’)]
>>> p = Path('C:/Users/Al/Desktop’)

>>> for textFilePO in p.glob('*.txt'):

... print(textFilePO) # Prints the Path object as a


string.

... # Do something with the text file.

...

C:\Users\Al\Desktop\foo.txt

C:\Users\Al\Desktop\spam.txt

C:\Users\Al\Desktop\zzz.txt
Checking Path Validity

• p.exists() returns True if the path exists or


returns False if it doesn’t exist.

• p.is_file() returns True if the path exists and is a


file, or returns False otherwise.

• p.is_dir() returns True if the path exists and is a


directory, or returns False otherwise.
THE FILE READING/WRITING
PROCESS
• Plaintext files contain only basic text characters and do
not include font, size, or color information.
Example: Text files with the .txt extension or Python
script files with the .py extension.
Your programs can easily read the contents of plaintext
files and treat them as an ordinary string value.
• Binary files are all other file types, such as word
processing documents, PDFs, images, spreadsheets, and
executable programs. If you open a binary file in
Notepad or TextEdit, it will look like scrambled nonsense,
Figure: The Windows calc.exe program opened in Notepad
File Read / write using
pathlib module
• The read_text() method returns a string of the
full contents of a text file.
• The write_text() method creates a new text file
(or overwrites an existing one) with the string
passed to it.
>>> from pathlib import Path
>>> p = Path('spam.txt')
>>> p.write_text('Hello, world!')
13
>>> p.read_text()
'Hello, world!'
There are three steps to reading or writing files
in Python:
1. Call the open() function to return a File object.
2. Call the read() or write() method on
the File object.
3. Close the file by calling the close() method on
the File object.
Opening Files with the open()
Function
>>> helloFile = open(Path.home() / 'hello.txt’)

>>> helloFile = open('C:\\Users\\


your_home_folder\\hello.txt’)

>>> helloFile =
open('/Users/your_home_folder/hello.txt')
• These commands will open the file in “reading plaintext” mode,
or read mode for short.

• When a file is opened in read mode, Python lets you only read data
from the file, you can’t write or modify it in any way.

• Read mode is the default mode for files you open in Python.

• But if you don’t want to rely on Python’s defaults, you can explicitly
specify the mode by passing the string value 'r' as a second
argument to open().

• The call to open() returns a File object. A File object represents a


file on your computer.
Reading the Contents of Files

• If you want to read the entire contents of a file as a


string value, use the File object’s read() method.

• you can use the readlines() method to get a list of


string values from the file, one string for each line of
text.
>>> helloContent = helloFile.read()
>>> helloContent
'Hello, world!’

>>> sonnetFile = open(Path.home() / 'sonnet29.txt')


>>> sonnetFile.readlines()
[When, in disgrace with fortune and men's eyes,\n',
'I all alone beweep my outcast state,\n’,

‘And trouble deaf heaven with my bootless cries,\n',


And look upon myself and curse my fate,']
Writing to Files
• You can’t write to a file you’ve opened in read mode,
though. Instead, you need to open it in “write plaintext”
mode or “append plaintext” mode.
• In short write mode and append mode
• Write mode will overwrite the existing file
• Pass 'w' as the second argument to open() to open the
file in write mode.
• Append mode, on the other hand, will append text to
the end of the existing file.
• Pass 'a' as the second argument to open() to open the
file in append mode.
>>> baconFile = open('bacon.txt', 'w')
>>> baconFile.write('Hello, world!\n')
13
>>> baconFile.close()

>>> 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.
SAVING VARIABLES WITH THE
SHELVE MODULE
• You can save variables in your Python programs to
binary shelf files using the shelve module.
• This way, your program can restore data to variables
from the hard drive.
• The shelve module will let you add Save and Open
features to your program.
• For example, if you ran a program and entered some
configuration settings, you could save those settings to
a shelf file and then have the program load them the
next time it is run.
>>> import shelve
>>> shelfFile = shelve.open('mydata')
>>> cats = ['Zophie', ‘Luna', 'Simon']
>>> shelfFile['cats'] = cats
>>> shelfFile.close()
>>> shelfFile = shelve.open('mydata')
>>> type(shelfFile)
<class 'shelve.DbfilenameShelf'>
>>> shelfFile['cats']
['Zophie’, ‘Luna', 'Simon']
>>> shelfFile.close()
SAVING VARIABLES WITH THE
PPRINT.PFORMAT() FUNCTION
• The pprint.pformat() function will return the contents of a list or
dictionary as a string.

• This string formatted to be easy to read, it is also syntactically


correct Python code.

• Say you have a dictionary stored in a variable and you want to save
this variable and its contents for future use.

• Using pprint.pformat() will give you a string that you can write to
a .py file. This file will be your very own module that you can import
whenever you want to use the variable stored in it.
>>> import pprint
>>> cats = [{'name': 'Zophie', 'desc':
'chubby'}, {'name': ‘Luna', 'desc': 'fluffy'}]
>>> pprint.pformat(cats)
"[{'desc': 'chubby', 'name': 'Zophie'}, {'desc':
'fluffy', 'name': ‘Luna'}]"
>>> fileObj = open('myCats.py', 'w')
>>> fileObj.write('cats = ‘ + pprint.pformat(cats) +
'\n')
83
>>> fileObj.close()
>>> import myCats
>>> myCats.cats
[{'name': 'Zophie', 'desc': 'chubby'}, {'name':
‘Luka', 'desc': 'fluffy'}]
>>> myCats.cats[0]
{'name': 'Zophie', 'desc': 'chubby'}
>>> myCats.cats[0]['name']
'Zophie'
PROJECT: ADDING BULLETS TO WIKI
MARKUP
The bulletPointAdder.py script will get the text from
the clipboard, add a star and space to the beginning
of each line, and then paste this new text to the
clipboard.
INPUT
Lists of animals
Lists of aquarium life
Lists of biologists by author abbreviation
OUTPUT
Lists of cultivars
* Lists of animals
* Lists of aquarium life
* Lists of biologists by author
abbreviation
* Lists of cultivars
Step 1: Copy and Paste from the
Clipboard
You want the bulletPointAdder.py program to do the
following:

1.Paste text from the clipboard.


2.Do something to it.
3.Copy the new text to the clipboard.
import pyperclip
text = pyperclip.paste()

# TODO: Separate lines and add stars.

pyperclip.copy(text)
Step 2: Separate the Lines of Text
and Add the Star
import pyperclip
text = pyperclip.paste()
# Separate lines and add stars.
lines = text.split('\n')
for i in range(len(lines)):

lines[i] = '* ' + lines[i]


pyperclip.copy(text)
Step 3: Join the Modified Lines

import pyperclip
text = pyperclip.paste()
# Separate lines and add stars.
lines = text.split('\n')
for i in range(len(lines)):

lines[i] = '* ' + lines[i]


text = '\n'.join(lines)
pyperclip.copy(text)
sorted() method
• The sorted() function returns a sorted list of the specified iterable
object.
• You can specify ascending or descending order.
• Strings are sorted alphabetically, and numbers are sorted numerically.

sorted(iterable, key=key, reverse=reverse)

iterable The sequence to sort, list, dictionary, tuple etc.


key Optional. A Function to execute to decide the order.
reverse Optional. A Boolean. False will sort ascending, True will sort descending.
Default is False
>>>sorted([3, 5, -1, 35, -27])

-27, -1, 3, 5, 35

>>>sorted((‘a’, ‘m’, ‘j’, ‘d’))

(‘a’, ‘d’, ‘j’, ‘m’)

>>>sorted((‘a’, ‘m’, ‘j’, ‘d’), reverse = True)

(‘m’, ‘j’, ‘d’, ‘a’)


Lambda fuctions
• A lambda function is a small anonymous function.
• A lambda function can take any number of arguments,
but can only have one expression.

lambda arguments : expression


>>> x = lambda a : a + 10
>>> print(x(5))
15

>>> x = lambda a, b : a * b
>>> print(x(5, 6))
30

>>> x = lambda a, b, c : a + b
+ c
>>> print(x(5, 6, 2))
13
Word_frequency = {‘joy’ : 10, ‘preksha’ : 13, ‘aman’: 7}

result = sorted(word_frequency.items(), key =


lambda kv: (kv[1], kv[0]),reverse = True)
PROJECT: GENERATING RANDOM
QUIZ FILES
# randomQuizGenerator.py - Creates quizzes with questions and answers in
# random order, along with the answer key.
import random
# The quiz data. Keys are states and values are their capitals.
capitals = {'Australia':'Canberra',
'India': 'New Delhi',
'Canada': 'Ottawa',
'China': 'Beijing',
'Egypt':'Cairo',
'fiji':'Suva',
'Nepal':'kathmandu',
'Pakistan': 'Islamabad',
'UK':'Londom',
'US':'Washington D.C.'}
for quizNum in range(5):
# Create the quiz and answer key files.
quizFile = open(f'capitalsquiz{quizNum + 1}.txt', 'w')
answerKeyFile = open(f'capitalsquiz_answers{quizNum + 1}.txt', 'w')
# Write out the header for the quiz.
quizFile.write('Name:\n\nDate:\n\nPeriod:\n\n')
quizFile.write((' ' * 20) + f'Country Capitals Quiz (Form{quizNum + 1})')
quizFile.write('\n\n')
# Shuffle the order of the states.
states = list(capitals.keys())
random.shuffle(states)
# Loop through all 10 states, making a question for each.
for questionNum in range(10):
# Get right and wrong answers.
correctAnswer = capitals[states[questionNum]]
wrongAnswers = list(capitals.values())
del wrongAnswers[wrongAnswers.index(correctAnswer)]
wrongAnswers = random.sample(wrongAnswers, 3)
answerOptions = wrongAnswers + [correctAnswer]
random.shuffle(answerOptions)
# Write the question and the answer options to the quiz file.
quizFile.write(f'Q{questionNum + 1}. What is the capital of {states[questionNum]}?\n')
for i in range(4):
quizFile.write(f" {'ABCD'[i]}. { answerOptions[i]}\n")
quizFile.write('\n')
# Write the answer key to a file.
answerKeyFile.write(f"{questionNum + 1}.{'ABCD'[answerOptions.index(correctAnswer)]}\n")
quizFile.close()
answerKeyFile.close()
Project: Multiclipboard
• The command line argument for the keyword is checked.
• If the argument is save, then the clipboard contents are saved to
the keyword.
• If the argument is list, then all the keywords are copied to the
clipboard.
• Otherwise, the text for the keyword is copied to the clipboard.

This means the code will need to do the following:

1.Read the command line arguments from sys.argv.


2.Read and write to the clipboard.
import shelve, pyperclip, sys

mcbShelf = shelve.open('mcb')

# TODO: Save clipboard content.


if len(sys.argv) == 3 and sys.argv[1].lower() == 'save':
mcbShelf[sys.argv[2]] = pyperclip.paste()

elif len(sys.argv) == 2:

# TODO: List keywords and load content.


if sys.argv[1].lower() == 'list':
pyperclip.copy(str(list(mcbShelf.keys())))
elif sys.argv[1] in mcbShelf:
pyperclip.copy(mcbShelf[sys.argv[1]])

mcbShelf.close()
Clipboard
• The clipboard, also known as pasteboard, is a location
on a computer, phone, or tablet memory that
temporarily stores cut or copied text or other data.

• Once something is stored in the clipboard, it can be


pasted to a new location as much as needed.

• The clipboard holds its information until you cut or copy


something else or log out of the computer.BACK TO SLIDE 36
Generator Function in Python
• A generator function in Python is defined like a normal
function, but whenever it needs to generate a value, it
does so with the yield keyword rather than return.
• If the body of a def contains yield, the function
automatically becomes a Python generator function.

glob() slide
Create a Generator in Python
In Python, we can create a generator function by simply
using the def keyword and the yield keyword. The
generator has the following syntax in Python:

def function_name():
yield statement
Generator Object
• Python Generator functions return a generator object that is iterable,
i.e., can be used as an Iterator.
• Generator objects are used either by calling the next method of the
generator object or using the generator object in a “for in” loop.
In this example, we will create a simple generator function in Python to
generate objects using the next() function.
# A generator function
def simpleGeneratorFun():
yield 1
yield 2
yield 3

# x is a generator object
x = simpleGeneratorFun()

# Iterating over the generator object using next

# In Python 3, __next__()
print(next(x))
print(next(x))
print(next(x))

You might also like