Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
18 views

Python Module 3

Uploaded by

pradeepshettar50
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views

Python Module 3

Uploaded by

pradeepshettar50
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 88

Module – 3

MANIPULATING STRINGS

1
Working with Strings
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.
String Literals
● Can we use a quote inside a string?
'That is Alice's cat.'
● Double quotes
"That is Alice's cat."
● Escape character
'Say hi to Bob\'s mother.'

5
print( ) using escape characters
& raw strings
print("Hello there!\nHow are you?\nI\'m doing fine.")

A raw string completely ignores all escape characters and prints any backslash
that appears in the string.

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


8
Multiline string with three single 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.
9
# Multiline
string using
single quote

# Multiline
string using
double quote
Without using multiline string
Multiline Comments
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.

12
Indexing and Slicing Strings
'Hello, world!'

Each string value can be thought of as


a list and each character in the string
as an item with a corresponding index
-ve index count from the end

13
Slicing string
The in and not in Operators with Strings
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.

15
Putting Strings Inside Other Strings

string interpolation using %s

f-strings, which is similar to string


interpolation except that braces are
used instead of %s

16
Built-in methods for string
manipulation
Useful String Methods

upper(), lower(), isupper(), and islower() Methods

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.
18
'abcABC'.islower()
False
'abcABC'.isupper()
False
'ABC'.isupper()
True
'1234ABC'.isupper()
True
'1234abc'.islower()
True
upper( ) and lower( ) chain

Since the upper() and lower()


string methods themselves
return strings, you can call
string methods on those
returned string values as well.

20
Nonletter characters in the string remain changed or unchanged

Asw: Unchanged

❑String 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() and
lower() on the string and then assign the new string to the variable
where the original was stored.
spam='Hello world!'
spam.upper()
spam
Output:
Hello world!
Guess the output:
for i in range(2,2):
spam='Hello world!'
print(i)
spam.upper()
spam
Output:
It will not print anything
Output:
Hello world!
When do we use upper ()and lower()
spam='Hello world!'
methods?
spam=spam.upper()
These methods are helpfull when you do
Spam
a case-insensitive comparison.
Output:
HELLO WORLD!
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

24
isX( ) examples

25
' '.isalpha()
'123'.isalnum()
False
True
'helloHello'.isalpha()
'abcAbc'.isalnum()
True
True
'hello123'.isalnum()
'This is String Methods'.istitle()
True
False
'01234'.isdecimal()
'This Is String Methods'.istitle()
True
True
'01234c'.isdecimal()
'This Is String METHODS'.istitle()
False
False
'hello123!'.isalnum()
False
‘ ’isspace()
True
‘\n’.isspace()
True
‘ My name ’.isspace()
False
‘ \n ’.isspace()
True
‘ \n hi ’.isspace()
False
The isX methods are helpful when you need to validate user
input.
Example:
The following program repeatedly asks user for their age and
a password until they provide valid input.
In the first while loop, we ask the user
for their age and store their
input in age. If age is a valid (decimal)
value, we break out of this first while
loop and move on to the second, which
asks for a password. Otherwise, we
inform the user that they need to enter a
number and again ask them to enter
their age.
In the second while loop, we ask for a
password, store the user’s input in
password, and break out of the loop if
the input was alphanumeric.
If it wasn’t, we’re not satisfied so we tell
the user the password needs to be
alphanumeric and again ask them to
enter a password.
Calling isdecimal() and isalnum()
on variables, we’re able to test
whether the values stored in those
variables are decimal or not,
alphanumeric or not. Here, these
tests help us reject the input forty
two and accept 42, andreject
secr3t! and accept secr3t.
startswith() and endswith()
The startswith() and endswith() methods return True if the string value they are called
on begins or ends (respectively) with the string passed to the method; otherwise, they
return False.

31
These methods are useful alternatives to the ‘==‘ operator.

'Hello World!'.startswith() 'Hello World!'.endswith(‘World')


Error False
'Hello World!'.startswith('Hello') 'My name is smitha'.endswith('smitha')
True True
'Hello World!'.startswith('HEllo')
False
'Hello World!'.endswith('Hello')
False
join() method
The join() method is useful when you have a list of strings that need to be joined
together into a single string value.

This method is called


on a string and
passed a list of string

33
split ( ) method
It does opposite to join()

It is called on a string value and return a list of


strings.

By default, the string 'My name is Simon' is split


wherever whitespace characters such as the
space, tab, or newline characters are found.
These whitespace characters are not included
in the strings in the returned list.

34
split ( ) using a delimiter
A common use of
split() is to split a
multiline string along
the newline
characters.

35
'My name is simon'.split('m')
spam='''Dear Alice
Output:
How are you doing?
['My na', 'e is si', 'on‘]
Please take care of your health'''
spam.split('\n')
spam='''Dear Alice
How are you doing?
Please take care of your health''' Output:
spam.split()
['Dear Alice', 'How are you doing?', 'Please
take care of your health']
Output:
['Dear', 'Alice', 'How', 'are', 'you',
'doing?', 'Please', 'take', 'care',
'of', 'your', 'health']
Splitting Strings with the partition() Method

If the separator string you pass to partition() occurs multiple times in the string that partition()
calls on, the method splits the string only on the first occurrence:

37
Using partition( ) for multiple assignment

38
>>>fruit,sep,vegetable='Apple Carrot'.partition(‘ ')
>>>vegetable
‘Carrot’
>>>fruit
‘Apple’
Justifying Text

rjust()
ljust()
center()

40
Justifying Text with rjust(), ljust(), and center()

❑ 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.

❑ An optional second argument to rjust() and ljust() will specify a fill


character other than a space character.
Justifying text

'Hello'.rjust(10) says that we want to right-justify


'Hello' in a string of total length 10. 'Hello' is five The center() string method works like
characters, so five spaces will be added to its left, ljust() and rjust() but centers the text
giving us a string of 10 characters with 'Hello' rather than justifying it to the left or right.
justified right.
42
The picnic items are displayed twice.The
In this program, we define a printPicnic() method first time the left column is 12 characters
that will take in a dictionary of information and wide, and the right column is 5 characters
use center(), ljust(), and rjust() to display that wide. The second time they are 20 and 6
information in a neatly aligned table-like format. characters wide, respectively.

In picnicItems, we have 4 sandwiches, 12 apples, 4 cups, and 8000 cookies.


We want to organize this information into two columns, with the name of the
item on the left and the quantity on the right.
Removing Whitespace with the strip(),
rstrip(), and lstrip() Methods
❑whitespace characters (space, tab, and
newline)
❑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
44
Numeric Values of Characters with
the ord() and chr() Functions
Every text character has a corresponding numeric value called a Unicode code
point. For example, the numeric code point is 65 for 'A'

The ord() function can be used to get the code point of a one-character string, and the
chr() function to get the one-character string of an integer code point

46
Ordering or mathematical operation
on characters

47
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 to an email, word
processor, or some other software.

NOTE: pyperclip module should be available in the local environment 48


Generate N prime number sequence
list=[]
for i in range(2,101):
flag=0
for j in range(2,i):
if i%j==0:
flag=1
break
if flag==0:
list.append(i)
print('The prime numbers are:',list)

Output:
The prime numbers are: [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61,
67, 71, 73, 79, 83, 89, 97]
Project
Reading and Writing Files
File Handling in Python
Files 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. For example:
there is a file on my Windows 7 laptop with the filename projects.docx in the
path C:\Users\asweigart\Documents.
The part of the filename after the last period is called the file’s extension and
tells you a file’s type.
❑project.docx is a Word document, and Users,
asweigart, and Documents all refer to folders/
directories
❑Folders can contain files and other folders.
For example, project.docx is in the Documents
folder, which is inside the asweigart folder, which is
inside the Users folder.
❑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 /.
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.
❑ This is simple to do with the os.path.join() function.
❑ If you pass it the string values of individual file and folder names in your path,
os.path.join() will return a string with a file path using the correct path separators.

54
❑ os.path.join('usr', 'bin', 'spam') returned 'usr\\bin\\
spam‘ in windows.
❑ If I had called this function on OS X or Linux, the
string would have been 'usr/bin/spam'.
❑ The os.path.join() function is helpful if you need
to create strings for filenames.

example joins names from a list of filenames to the


end of a folder’s name
Filesystem in UNIX

56
File handling commands in UNIX

pwd : present working directory

ls : list files

Home Directory (/)

cd : change directory

cd / : change to root directory

mkdir : make directory / create directory

Copy and move commands: cp and mv

57
pathlib module in python
● A built-in module called pathlib is available in python 3.4
onwards for handling files.

● File management includes creating, moving, copying, and


deleting files and directories, checking if a file or directory
exists,and so on.

58
The Current Working Directory
❑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().
●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.”
61
(dot) and (dot dot) operators

. (this directory)
Demo in Terminal .. (parent directory)

62
Creating New Folders with os.makedirs()

This will create not just the C:\delicious folder


but also a walnut folder inside C:\delicious
and a waffles folder inside C:\delicious\
walnut. That is,
os.makedirs() will create any necessary
intermediate folders in order to ensure that the
full path exists.
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. 66
Finding File Sizes and Folder Contents
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

68
dirname and basename
os.path.split()

If you need a path’s dir name and base name together, you can just call
os.path.split() to get a tuple value with these two strings, like so:
os.path.sep()
Finding File Sizes and Folder Contents

• 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. (Note that this function is in the os module, not
os.path.)
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) returns True if the path exists or
returns False if it doesn’t exist.
● Calling os.path.isfile(path) returns True if the path exists and is
a file, or returns False otherwise.
● Calling os.path.isdir(path) returns True if the path exists and is
a directory, or returns False otherwise.

75
The File Reading/Writing Process
❑ The functions covered in the next few sections will apply to plaintext files.
❑ Plaintext files contain only basic text characters and do not include font,
size, or color information.
❑ Text files with the .txt extension or Python script files with the .py
extension are examples of plaintext files.
❑ 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, like in
Three steps to reading or writing files in Python

Call the open() function to return a File object.


1) Call the read() or write() method on the File object.
2) Close the file by calling the close() method on the File
object.

79
Binary Files
● Opening a calc.exe in windows using notepad

80
Opening Files with the open() Function
To open a file with the open() function, you pass it a string path indicating
the file you want to open; it can be either an absolute or relative path. The
open() function returns a File object.

open('/Users/asweigart/hello.txt', 'r')
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.
use the readlines() method to get a list of string
values from the file, one string for each line of
text.
To read the content of the file line by line there are 3
commands:
Writing to Files

❑Similar to how the print() function “writes”


strings to the screen.
❑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.
Before After

Before After
5. Develop a program to print 10 most frequently appearing words in a text file. [Hint:
Use dictionary with distinct words and their frequency of occurrences. Sort the
dictionary in the reverse order of frequency and display dictionary slice of first 10
items]
OUTPUT

You might also like