Strings
String values in Python code begin and end with a single quote
What if a string itself contains a single quote?
To use string inside a quote
Double quotes
Escape characters
Strings can begin and end with double quotes
A string can have a single quote character if it is enclosed in
double quotes
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.
What if you need a \ in your string?
An r is placed before the beginning quotation mark of a string to
make it a raw string.
A raw string completely ignores all escape characters and prints any
backslash that appears in the string
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
Escaping single and double quotes is optional in multiline strings
While the hash character (#) marks the beginning of a comment,
for the rest of the line, a multiline string is often used for
comments that span multiple lines.
Strings use indexes and slices the same way lists do. You can think
of the string 'Hello world!' as a list and each character in the string
as an item with a corresponding index.
Specifying an index, returns a single character at that position in
the string.
Specifying a range from one index to another, returns a string of
characters.
The starting index is included and the ending index is not.
The in and not in operators can be used with strings just like with
list values.
An expression with two strings joined using in or not in will
evaluate to a Boolean True or False.
These expressions test whether the first string (the exact string,
case sensitive) can be found within the second string.
The upper() and lower() string methods return a new string
where all the letters in the original string have been converted to
uppercase or lowercase, respectively
Non-letter characters in the string remain unchanged
These methods do not change the string itself but return new
string values
The isupper() and islower() methods will return a Boolean True
value if the string has at least one letter and all the letters are
uppercase or lowercase, respectively. Otherwise, the method
returns False.
upper() and lower() string methods themselves return strings.
These string methods can be called on those returned string values
as well.
The isX String Methods
• Along with islower() and isupper(), there are several string methods
that have names beginning with the word is.
• These methods return a Boolean value that describes the nature of the
string.
The isX String Methods
❖isalpha() returns True if the string consists only of letters and is not 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 new-
lines 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.
The isX String Methods
The isX string methods are helpful when you need to validate user
input. For example, the following program repeatedly asks users for their
age and a password until they provide valid input.
Output:
The startswith() and endswith() Methods
startswith() method returns True if the string value begins with
the string passed to the method
endswith() method returns True if the string value ends with the
string passed to the method
Otherwise, they return False
These methods are useful alternatives to the == equals operator
The startswith() and endswith() Methods
join() method
The join() method is useful to join a list of strings into a single
string
The string join() calls on is inserted between each string of the list
argument
A list of strings is passed to join method
It returns a string
split() method
The split() method splits a string wherever whitespace characters
such as the space, tab, or newline characters are found
A list of strings is passed to join method
It returns a string
split() method
A common use of split() is to split a multiline string along the
newline characters. Enter the following into the interactive shell:
Justifying Text with the rjust(), ljust(), and
center() Methods
rjust() and ljust() returns right and left justified string
center() centers the text rather than justifying
Whitespaces are inserted to justify the text
2 arguments
first argument to both methods is an integer length for the justified string
An optional second argument will specify a fill character other than a space
character
Justifying Text with the rjust(), ljust(), and
center() Methods
Justifying Text with the rjust(), ljust(), and
center() Methods
These methods are especially useful when you need to print
tabular data that has the correct spacing.
Output:
Removing Whitespace with the strip(),
rstrip(), and lstrip() Methods
Used to rip off whitespace characters (space, tab, and newline)
from 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
Removing Whitespace with the strip(), rstrip(),
and lstrip() Methods
• Optionally, a string argument will
specify which characters on the ends
should be stripped.
• 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').
Numeric Values of Characters with the ord() and
chr() Functions
Every text character has a corresponding numeric value called a
Unicode code point
ord() function is used to get the code point of a one-character
string
The chr() function is used to get the one-character string of an
integer code point.
Numeric Values of Characters with the ord()
and chr() Functions
Copying and Pasting Strings with the pyperclip
Module
The pyperclip module has copy() and paste() functions
The copy() and paste() functions can send text to and receive text
from computer’s clipboard
If something outside of the program changes the clipboard contents,
the paste() function will return it.
Reverse string (Using loop)
Reverse string (Using recursion)
Output:
The original string is : Computer Science
The reversed string(using recursion) is : ecneicS retupmoC
Reverse string (Using extended slice syntax)
Output:
The original string is : Bengaluru
The reversed string(using extended slice syntax) is : urulagneB
Reverse string (Using reversed)
Output:
The original string is : Python Programming
The reversed string(using reversed) is : gnimmargorP nohtyP
Python program to check if a string is palindrome or not
Method #1
1. Find reverse of string
2. Check if reverse and original are same or not.
Python program to check if a string is palindrome or not
Method #2: Iterative Method
Run a loop from starting to length/2 and check the first character to the last
character of the string and second to second last one and so on …. If any
character mismatches, the string wouldn’t be a palindrome.
Python program to check if a string is palindrome or not
Method #3: Using the inbuilt function to reverse a string
In this method, predefined function ‘ ‘.join(reversed(string)) is used to reverse
string.
Python program to check if a string is palindrome or not
Method #4: using one extra variable
In this method user take a character of string one by one and store in an
empty variable. After storing all the character user will compare both the
string and check whether it is palindrome or not.
Python program to check if a string is palindrome or not
Method using flag: In this method user compare each
character from starting and ending in a for loop and if the
character does not match then it will change the status of
the flag. Then it will check the status of flag and accordingly
and print whether it is a palindrome or not.
Method using recursion: This method compares the first
and the last element of the string and gives the rest of the
substring to a recursive call to itself.
Python program to check if a string is palindrome or not
Python Program to Remove Punctuations From a String
Output:
Hello he said and went
Python Program to Display Fibonacci Sequence Using Recursion
Python Program to Find Sum of Natural Numbers Using Recursion
Output:
The sum is 1275
Python Program to Convert Decimal to Binary Using Recursion
Decimal number is converted
into binary by dividing the
number successively by 2 and
printing the remainder in
reverse order.
Output:
100010
Inverted half pyramid using *and numbers
Program to print full pyramid using *
Program to print full pyramid using numbers
Reverse a Number using a while loop Reverse a Number Using String slicing
Output:
654321
Output:
4321
Python Program to Compute the Power of a Number using while loop, for
loop and pow() function
Output:
Answer = 81
Python Program to Count the Number of Occurrence
of a Character in String
Output:
2
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 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.
The password manager program you’ll create in this example
isn’t secure, but it offers a basic demonstration of how such
programs work.
Project: Password Locker
Step 1: Program Design and Data Structures
The dictionary will be the data structure that organizes your
account and password data. Make your program look like the
following:
Project: Password Locker
Step 2: Handle Command Line Arguments
The command line arguments will be stored in the variable sys.argv.
The first item in the sys.argv list should always be a string containing
the program’s filename ('pw.py'), and the second item should be the
first command line argument. For this program, this argument is the
name of the account whose password you want.
Project: Password Locker
Step 3: Copy the Right Password
Now that the account name is stored as a string in the variable
account, you need to see whether it exists in the PASSWORDS
dictionary as a key. If so, you want to copy the key’s value to the
clipboard using pyperclip.copy(). (Since you’re using the pyperclip
module, you need to import it.)
Project: Adding Bullets to Wiki Markup
The python 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. For example, if you copied the following
text (for the Wikipedia article “List of Lists of Lists”) to the
clipboard:
and then ran the python program, the clipboard would then
contain the following:
Project: Adding Bullets to Wiki Markup
Step 1: Copy and Paste from the Clipboard
Step 2: Separate the Lines of Text and Add the Star
Step 3: Join the Modified Lines
Reading and Writing files
Introduction
Variables are a way to store data while a program is running
If your data has to exist even after the program has finished
execution , it has to be saved as a file
Python can be used to create, read, and save files on the hard
drive.
File and File Paths
File and File paths
A file has two key properties: a filename (usually written as one
word) and a path
The path specifies the location of a file on the computer.
C:\Users\Public\Pictures\SamplePictures\Chrysanthemum.jpg
The part of the filename after the last period is called the file’s
extension and specifies file’s type E.g .jpg
Users, Public, Pictures and Sample Pictures are names of folders
Folders can contain files and other folders
The C:\ part of the path is the root folder, which contains all
other folders
Backslash on Windows and Forward Slash on
macOS and Linux
On Windows, paths are written using backslashes (\) as the
separator between folder names
The macOS and Linux operating systems, use the forward
slash (/) as their path separator
Python scripts should handle both cases
Backslash on Windows and Forward Slash on
macOS and Linux
If a string of individual file names are passed, path should be
returned using correct separators
This can be done in two ways
The Path() function in the pathlib module
os.path.join() function in the os module
Backslash on Windows and Forward Slash on
macOS and Linux
Backslash on Windows and Forward Slash on
macOS and Linux
The following code joins names from a list of filenames to the
end of a folder’s name
Using the / Operator to Join Paths
The / operator can combine
Path objects and strings.
This is helpful for modifying
a Path object after it is
created
This is done with the Path()
function.
Python evaluates the /
operator from left to right
Using the / Operator to Join Paths
When using the / operator for joining paths one of the first two
values must be a Path object.
The / operator replaces the older os.path.join() function
The Current Working Directory
Every program that runs on your computer has a current
working directory, or cwd.
Folder is the modern term used for directories
However, current working directory is the standard term in
use
The current working directory can be obtained with the
Path.cwd() function
The Current Working Directory
Current working directory can be changed using os.chdir()
from os module
The Current Working Directory
Python will display an error if you try to change to a directory that
does not exist
Absolute vs Relative Paths
2 ways to specify a file path
Absolute Path
Relative Path
An absolute path, which always begins with the root folder
A relative path, which is relative to the program’s current working
directory
Absolute vs Relative Paths
the dot (.)
dot-dot (..) folders
A single dot for a folder name is
shorthand for this directory
Two dots means the parent folder
In the given example, the cwd is
set to C:\bacon
The .\ at the start of a relative path is optional. For example, .\spam.txt and spam.txt
refer to the same file.
Creating New Folders Using the
os.makedirs() Function
New folders can be created with os.makedirs() function
Handling Absolute and Relative Paths
The os.path module provides functions for returning the absolute path of a
relative path and for checking whether a given path is an absolute path
Calling os.path.abspath(path) will return a string of the absolute path of the
argument. This is an easy way to convert a relative path into an absolute one.
Calling os.path.isabs(path) will return True if the argument is an absolute
path and False if it is a relative path.
Calling 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.
Getting the Parts of a File Path
Different parts can be extracted from a 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)
Windows Path objects have a drive attribute, but macOS and Linux Path objects
don’t
Getting the Parts of a File Path
Fig: The parts of a Windows (top) and macOS/Linux (bottom) file path
Getting the Parts of a File Path
Contd.,
os.path.split() does not take a file path and return a list of strings
of each folder.
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.
os.path.getsize(path) will return the size in bytes of the file in
the path argument
Finding File Sizes and Folder Contents
os.listdir(path) will return a list of filename strings for each file in the
path argument.
Finding
File Total File Sizes in a Folder Contents
If you want to find the total size of all the files in this directory,
we can use os.path.getsize() and os.listdir() together
Checking Path Validity
Calling os.path.exists(path) will return True if the file or
folder referred to in the argument exists and will return
False if it does not exist.
Calling os.path.isfile(path) will return True if the path
argument exists and is a file and will return False otherwise.
Calling os.path.isdir(path) will return True if the path
argument exists and is a folder and will return False
otherwise.
Checking Path Validity
os.path.exists('h:\\')
The File Reading/Writing Process
The File Reading/Writing Process
Plaintext files - contain only basic text characters and do not
include font, size, or color information
E.g. files with .txt, .py extension which can be opened with Notepad
Binary files are all other file types, such as word processing
documents, PDFs, images, spreadsheets, and executable programs
If a binary file is opened in Notepad or TextEdit, it will look like
scrambled text
The File Reading/Writing Process
The pathlib module’s read_text()
method returns a string of the
full contents of a text file.
Its write_text() method creates a
new text file (or overwrites an
existing one) with the string
passed to it.
The File Reading/Writing Process
The File Reading/Writing Process
There are three steps to reading or writing files in Python:
Call the open() function to return a File object
Call the read() or write() method on the File object
Close the file by calling the close() method on the File object
Opening Files with the open() Function
The open() function returns a File object
The path indicating the file to be opened is passed to open()
function
Reading the Contents of Files
read() function is used to read from a file
Reading the Contents of Files
readlines() method to get a list of string values from the file,
one string for each line of text
Except for the last line of the file, each of the string values
ends with a newline character ‘\n’
Writing to Files
You can’t write to a file you’ve opened in read mode
A file should be opened in write mode or append mode for
writing
If the filename passed to open() does not exist, both write
and append mode will create a new, blank file
After reading or writing a file, call the close() method before
opening the file again
Writing to Files
Write mode will overwrite the existing file and start from
scratch by calling write() on an opened file
'w' is passes as the second argument to open() to open a file
in write mode
Writing to Files
Append mode, on the other hand, will append text to the
end of the existing file by calling write() on an opened file
'a' is passed as the second argument to open() to open a file
in append mode.
Saving Variables with the shelve Module
Saving Variables with the shelve Module
Variables in a Python program can be stored to binary shelf
files
Program can restore data to variables from the hard drive
shelve module must be imported
A filename is passed to shelve.open() and pass it, and then
store the returned shelf value in a variable
When you’re done, call close() on the shelf value
On Windows OS three new files in the current working
directory are created: mydata.bak,mydata.dat, and mydata.dir
These binary files contain the data stored in the shelf
Saving Variables with the shelve Module
Saving Variables with the pprint.pformat()
Function
Saving Variables with the pprint.pformat()
Function
Using pprint.pformat() will give a string that can be witten to a
.py file.
This file will be a module that can be imported when required
to use the variable stored in it.
Saving Variables with the pprint.pformat()
Function