0% found this document useful (0 votes)
2 views51 pages

Module3 Strings

This document provides an overview of string manipulation in Python, covering how to create strings using quotes, escape characters, and raw strings. It also explains string indexing, slicing, and various string methods such as upper(), lower(), isX() methods, and how to handle file paths using the os and pathlib modules. Additionally, it discusses creating directories, checking path validity, and retrieving file information.

Uploaded by

nooresaba799
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views51 pages

Module3 Strings

This document provides an overview of string manipulation in Python, covering how to create strings using quotes, escape characters, and raw strings. It also explains string indexing, slicing, and various string methods such as upper(), lower(), isX() methods, and how to handle file paths using the os and pathlib modules. Additionally, it discusses creating directories, checking path validity, and retrieving file information.

Uploaded by

nooresaba799
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

MODULE 3

MANIPULATING STRINGS
MANIPULATING STRINGS
WORKING WITH STRINGS
Multiple ways to type strings

[Link] Quotes

● Strings can begin and end with double quotes, just as they do with single quotes.

spam = "That is Alice's cat."

Since the string begins with a double quote, Python knows that the single quote is part of the string and
not marking the end of the string
[Link] 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.
For example, the escape character for a single quote is \'. We can use this inside a string that
begins and ends with single quotes.

spam = 'Say hi to Rahul\'s mother.'


o/p: Say hi to Rahul's mother.
> print("Hello there!\nHow are
you?\nI\'m doing fine.")

Hello there!

How are you?

I'm doing fine.


Raw String

Placing an r before the beginning >> print(r'That is Carol\'s


cat.')
quotation mark of a string to make it a
raw string. That is Carol\'s cat.

A raw string completely ignores all


escape characters and prints any
backslash that appears in the string.
Multiline Strings with Triple Quotes

A multiline string in Python begins and print('''Dear Alice,

ends with either three single quotes or


three double quotes. Any quotes, tabs, Eve's cat has been arrested for catnapping, cat
or newlines in between the “triple burglary, and extortion.

quotes” are considered part of the string.


Python’s indentation rules for blocks do Sincerely,
not apply to lines inside a multiline Bob''')
string.
Indexing and Slicing Strings

● Strings use indexes and slices the ' H e l l o w o r l d ! '


same way lists do.
● string 'Hello world!' as a list 0 1 2 3 4 5 6 7 8 9 10 11
and each character in the
string as an item with a
corresponding index. 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.
>>> spam = 'Hello, world!'
By slicing and storing the resulting substring
>>> spam[0] in another variable, you can have both the
'H' whole string and the substring handy for
>>> spam[4] quick, easy access.
'o'

>>> spam[-1]

'!'

>>> spam[0:5]

'Hello'

>>> spam[:5]

'Hello'

>>> spam[6:]

'world!'
The in and not in Operators with Strings

>> 'Hello' in 'Hello, World' TRUE


The in and not in operators can be
used with strings just like with list >> 'HELLO' in 'Hello, World'

values. An expression with two FALSE

strings joined using in or not in will


evaluate to a Boolean True or False. >>'cats' not in 'cats and dogs'

FALSE
USEFUL STRING METHODS

The upper() and lower() string >>> spam = 'Hello, world!'


methods return a new string where
>>> spam = [Link]()
all the letters in the original string
have been converted to uppercase 'HELLO, WORLD!'
or lowercase, respectively.

>> spam = [Link]()


'hello, world!'
to
spam = [Link]() print('How are you?')
change the string in spam feeling = input()
instead of simply
if [Link]() == 'great':
[Link]().
print('I feel great too.')
else:
The upper() and lower() methods are
helpful if you need to make a print('I hope the rest of your day is
case-insensitive comparison. good.')

entering a variation on great, such as


GREat,

I feel great too.


The isupper() and islower() methods >> spam = 'Hello, world!'
will return a Boolean True value if the >> [Link]()
string has at least one letter and all the
letters are uppercase or lowercase, False
respectively. >>[Link]()

FALSE

>>'HELLO'.isupper()

TRUE

>>'abc12345'.islower()
The upper() and lower() string methods themselves return strings, you can
call string methods on those returned string values as well.

'Hello'.upper()

'HELLO'

>>> 'Hello'.upper().lower()

'hello'

>>> 'Hello'.upper().lower().upper()

'HELLO'

>>> 'HELLO'.lower()

'hello'

>>> 'HELLO'.lower().islower()

True
The isX() Methods:Along with islower() and isupper(), there are several other string
methods that have names beginning with the word is. These methods return a Boolean
value that describes the nature of the string.

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() >>> ' '.isspace()
True True
>>> 'hello123'.isalpha() >>> 'This Is Title Case'.istitle()
False True
>>> 'hello123'.isalnum() >>> 'This Is Title Case 123'.istitle()

True True
>>> 'hello'.isalnum() >>> 'This Is not Title Case'.istitle()

True False
>>> '123'.isdecimal() >>> 'This Is NOT Title Case Either'.istitle()

True False
Following program repeatedly asks users for their age and a password until they provide
valid input.

while True:
OUTPUT:
print('Enter your age:')

age = input()

if [Link](): [Link]
break

print('Please enter a number for your age.')

while True:

print('Select a new password (letters and


numbers only):')

password = input()

if [Link]():

break

print('Passwords can only have letters and


numbers.')
The startswith() and endswith() Methods

>>> 'Hello, world!'.startswith('Hello')


The startswith() and endswith() methods
return True if the string value they True

are called on begins or ends >>> 'Hello, world!'.endswith('world!')

(respectively) with the string True

passed to the method; otherwise, >>> 'abc123'.startswith('abcdef')

they return False. False

>>> 'abc123'.endswith('12')

False

>>> 'Hello, world!'.startswith('Hello, world!')

True

>>> 'Hello, world!'.endswith('Hello, world!')

True
The join() and split() Methods

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


● The join() method is useful when you
have a list of strings that need to be 'cats, rats, bats'

joined together into a single string >>> ' '.join(['My', 'name', 'is', 'Simon'])
value.
'My name is Simon'

>>> 'ABC'.join(['My', 'name', 'is', 'Simon'])

'MyABCnameABCisABCSimon'
The split() method : It’s called on a string value and returns a list of strings.

>>> 'My name is Simon'.split() >>> 'MyABCnameABCisABCSimon'.split('ABC')

['My', 'name', 'is', 'Simon'] ['My', 'name', 'is', 'Simon']

By default, the string 'My name is Simon' is split >>> 'My name is Simon'.split('m')

wherever whitespace characters such as ['My na', 'e is Si', 'on']


the space, tab, or newline characters are
found.
Justifying Text with the rjust(), ljust(), and center() Methods

The rjust() and ljust() string methods >>> 'Hello'.rjust(10)


return a padded version of the string ' Hello'
they are called on, with spaces
inserted to justify the text. The first >>> 'Hello'.rjust(20)
argument to both methods is an
integer length for the justified string. ' Hello'
>>> 'Hello, World'.rjust(20)

' Hello, World'

>>>>>'Hello'.ljust(10)
'Hello '
An optional second argument to rjust() and ljust() will specify a fill character other than
a space character.

>>> 'Hello'.rjust(20, '*') The center() string method works


like ljust() and rjust() but centers the
'***************Hello' text rather than justifying it to the
>>> 'Hello'.ljust(20, '-') left or right.

'Hello---------------' >>> 'Hello'.center(20)

' Hello '

>>> 'Hello'.center(20, '=')

'=======Hello========'
Removing Whitespace with the strip(), rstrip(), and lstrip() Methods

The strip() string method will >>> spam = ' Hello, World '
return a new string without any >>> [Link]()
whitespace characters at the 'Hello, World'
beginning or end. >>> [Link]()
'Hello, World '
The lstrip() and rstrip() methods will
>>> [Link]()
remove whitespace characters from the ' Hello, World'
left and right ends, respectively.
PYPERCLIP PROJECT

PASSWORD LOCKER PROJECT

Adding bullets to wiki markup


READING AND WRITING FILES:FILES AND FILE PATHS
A file has two key properties: For example, there is a file on my Windows
● filename (usually written as one word) laptop with the filename [Link] in the
● path. path C:\Users\Al\Documents.

The path specifies the location of a file on The part of the filename after the last period is
the computer. called the file’s extension and tells a file’s type.
The C:\ part of the path is the root folder, We normally use the + operator to add two
which contains all other folders. integer or floating-point numbers, such as in
the expression 2 + 2, which evaluates to the
● On Windows, paths are written using
integer value 4.
backslashes (\) as the separator
between folder names. Similarly, the / operator that we normally use for
● The macOS and Linux operating division can also combine Path objects and strings.
systems, however, use the forward >>> from pathlib import Path
slash (/) as their path separator. >>> Path('spam') / 'bacon' / 'eggs'
WindowsPath('spam/bacon/eggs')
● To get a simple text string of the >>> Path('spam') / Path('bacon/eggs')
path, pass it to the str() function. WindowsPath('spam/bacon/eggs')
>>> Path('spam') / Path('bacon',
'eggs')
WindowsPath('spam/bacon/eggs')
The Current Working Directory

● Every program that runs on >>> from pathlib import Path


computer has a current working >>> import os
directory, or cwd.
>>> [Link]()
● current working directory as a
string value with the [Link]() WindowsPath('C:/Users/Al/AppData/Local/Program
s/Python/Python37')'
function
● change it using [Link](). >>> [Link]('C:\\Windows\\System32')

>>> [Link]()

WindowsPath('C:/Windows/System32')
Absolute vs. Relative Paths

● An absolute path, which always A single period (“dot”) for a folder name is
begins with the root folder shorthand for “this directory.”
● A relative path, which is relative to
the program’s current working Two periods (“dot-dot”) means “the
directory parent folder.”

There are also the dot (.) and dot-dot (..)


folders.
Feature Absolute Path Relative Path

Starting Point Root Directory Current Working Directory

Location Fixed, unambiguous, from Dependent on current


root directory, not fixed

Dependence Independent of the current Dependent on the current


working directory. working directory.
Creating New Folders Using the [Link]() Function

programs can create new folders (directories) with the [Link]() function.
import os
[Link]('C:\\delicious\\walnut\\waffles')

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, [Link]() will create any necessary intermediate folders in order to
ensure that the full path exists.
Handling Absolute and Relative Paths

The pathlib module provides methods for checking whether a given path is an absolute path and
returning the absolute path of a relative path.

● Calling the is_absolute() method on a Path object will return True if it represents an
absolute path or False if it represents a relative path.

>>> [Link]()
WindowsPath('C:/Users/Al/AppData/Local/Programs/Python/Python37')
>>> [Link]().is_absolute()
True
>>> Path('spam/bacon/eggs').is_absolute()
False
The [Link] module also has some useful functions related to absolute and relative paths:

● Calling [Link](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 [Link](path) will return True if the argument is an absolute path and False if it is a
relative path.
● Calling [Link](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[Example Prog]

● 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)

Note that Windows Path objects have a drive


attribute, but macOS and Linux Path objects don’t.
The drive attribute doesn’t include the first backslash.
>>> p = Path('C:/Users/Al/[Link]')

>>> [Link]

'C:\\'

>>> [Link] # This is a Path object, not a string.

WindowsPath('C:/Users/Al')

>>> [Link]

'[Link]'

>>> [Link]

'spam'

>>> [Link]

'.txt'

>>> [Link]

'C:'
>>> calcFilePath = 'C:\\Windows\\System32\\[Link]'

>>> [Link](calcFilePath)

'[Link]'

>>> [Link](calcFilePath)

'C:\\Windows\\System32'
If we need a path’s dir name and base name together, just call
[Link]() to get a tuple value with these two strings, like so:

>>> calcFilePath = 'C:\\Windows\\System32\\[Link]'

>>> [Link](calcFilePath)

('C:\\Windows\\System32', '[Link]')
create the same tuple by calling [Link]() and [Link]() and placing their
return values in a tuple:

>>> ([Link](calcFilePath), [Link](calcFilePath))

('C:\\Windows\\System32', '[Link]')
Finding File Sizes and Folder Contents

The [Link] module provides functions for finding the size of a file in bytes and
the files and folders inside a given folder.

● Calling [Link](path) will return the size in bytes of the file in


the path argument.
● Calling [Link](path) will return a list of filename strings for each
file in the path argument.
[Link]('C:\\Windows\\System32\\[Link]')

27648
Checking Path Validity

Many Python functions will crash with an error if you supply them with a path that does
not exist.

Pathobjects have methods to check whether a given path exists and whether it is a file or
folder.

● Calling [Link]() returns True if the path exists or returns False if it doesn’t exist.
● Calling p.is_file() returns True if the path exists and is a file, or returns False otherwise.
● Calling p.is_dir() returns True if the path exists and is a directory, or returns False
otherwise.
THE FILE READING/WRITING PROCESS: File handling refers to the process of performing operations on a file
such as creating, opening, reading, writing and closing it, through a programming interface.

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.
from pathlib import Path ● This method calls create a [Link] file with the
p = Path('[Link]') content 'Hello, world!'.
p.write_text('Hello, world!') ● The 13 that write_text() returns indicates that 13
13 characters were written to the file.
p.read_text() ● The read_text() call reads and returns the contents of
'Hello, world!' our new file as a string: 'Hello, world!'.

VTU Q.P: Explain the process of File Handling also explain reading and writing process with
suitable example
The more common way of writing to a file involves using the open() function and file objects.
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 Reading files with read()

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

File = open('D:\PYTHON_PRGS\[Link]')
print([Link]())

● Above Command will open the file in “reading plaintext” mode, or read mode for short.
● When a file is opened in read mode, Python lets only to read data from the file.
● We can’t write or modify it in any way.
● Read mode is the default mode for files you open in Python. We can explicitly specify the mode by
passing the string value 'r' as a second argument to open(). So open('/Users/Al/[Link]', 'r') and
open('/Users/Al/[Link]') do the same thing.
Mode Description Behavior

r Read-only mode. Opens the file for reading. File must exist; otherwise, it raises an error.

Opens the file for writing. Creates a new file or truncates the existing
w Write mode.
file.

a Append mode. Opens the file for appending data. Creates a new file if it doesn't exist.
Reading the Contents of Files

● 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
Writing to Files

● We can’t write to a file opened in read mode


● To Write into file open it in “write plaintext” mode or “append plaintext” mode, or
write mode and append mode for short
● 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.
● Ex : baconFile = open('[Link]', 'w')
SAVING VARIABLES WITH THE SHELVE MODULE

● The shelve module in Python allows to save variables to a file, which can be accessed later.
It acts like a persistent dictionary to store and retrieve objects using keys.
● The shelve module will allow to add Save and Open features to program.

>>> import shelve


>>> shelfFile = [Link]('mydata') [To pass the open() shelf method filenames as strings.]
>>> cats = ['Zophie', 'Pooka', 'Simon']
>>> shelfFile['cats'] = cats
>>> [Link]()
To retrieve the data from shelf files: Shelf values don’t have to be opened in read or write mode—they can
do both once opened.

>>> shelfFile = [Link]('mydata')

>>> type(shelfFile)

<class '[Link]'>

>>> shelfFile['cats']

['Zophie', 'Pooka', 'Simon']

>>> [Link]()
● Variables can be stored in Python programs to binary shelf files using the SHELVE module.
● The shelve module will let us to add Save and Open features to your program.

import shelve s = [Link]('mydata')


#s = [Link]('mydata') type(s)
#s['name']= "Rahul" print(s['name'])
#s['physics']=99 print(list([Link]()))
#s['Chemistry']=90 [Link]()
#s['BIOLOGY']=85
#[Link]()
SAVING VARIABLES WITH THE [Link]() FUNCTION

● [Link]() function will return same text as a string instead of printing it.
● Using [Link]() will give a string that you can write to a .py file.
● This file will be own module that we can import whenever we want to use the
variable stored in it.

You might also like