MOD 3 Introduction to Python Programming (BPLCK105B)
MODULE -3
VTU Questions Paper Solution
1. Explain Python string handling methods with examples: split(),endswith(), ljust(),
center(), lstrip() (10M)
i. split()
The split() method is called on a string value and returns a list of strings.
We can pass a delimiter string to the split() method to specify a different string to
split upon.
common use of split() is to split a multiline string along the newline characters
Example:
ii. 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.
These methods are useful alternatives to the == equals operator if we need to check
only whether the first or last part of the string, rather than the whole thing, is equal
to another string.
Example:
Meghashree, CSE (ICSB) PA College of Engineering Page 1
MOD 3 Introduction to Python Programming (BPLCK105B)
iii. 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.
'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.
The center() string method works like ljust() and rjust() but centers the text
rather than justifying it to the left or right
These methods are especially useful when you need to print tabular data that
has the correct spacing.
Example
Meghashree, CSE (ICSB) PA College of Engineering Page 2
MOD 3 Introduction to Python Programming (BPLCK105B)
2. Explain Python string handling methods with examples: join(), startswith(),rjust(),strip(),rstrip()
(10 M)
i. join()
The join() method is useful when we 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.
The returned string is the concatenation of each string in the passed-in list.
string join() calls on is inserted between each string of the list argument.
Ex: when join(['cats', 'rats', 'bats']) is called on the ', ' string, the returned string is 'cats,
rats, bats'.
join() is called on a string value and is passed a list value.
ii. startswith()
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.
These methods are useful alternatives to the == equals operator if we need to check only
whether the first or last part of the string, rather than the whole thing, is equal to another
string
Meghashree, CSE (ICSB) PA College of Engineering Page 3
MOD 3 Introduction to Python Programming (BPLCK105B)
iii. rjust(Refer Previous Question)
iv. strip(),rstrip()
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.
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').
3. Explain with suitable Python program segments: (i) os.path.basename() (ii) os.path.join()
(5M)
i. os.path.basename
Calling os.path.basename(path) will return a string of everything that comes after the last
slash in the path argument
In Figure: The base name follows the last slash in a path and is the same as the filename.
The dirname is everything before the last slash
Meghashree, CSE (ICSB) PA College of Engineering Page 4
MOD 3 Introduction to Python Programming (BPLCK105B)
For Example
>>> path = 'C:\\Windows\\System32\\calc.exe'
>>> os.path.basename(path)
'calc.exe'
>>> os.path.dirname(path)
'C:\\Windows\\System32'
ii. os.path.join()
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.
Fortunately, this is simple to do with the os.path.join() function.
If you 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'
The os.path.join() function is helpful if you need to create strings for filenames.
4. Explain reading and saving python program variables using shelve module with suitable
Python program.(6M)
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', 'Pooka', 'Simon']
>>> shelfFile['cats'] = cats
>>> shelfFile.close()
Meghashree, CSE (ICSB) PA College of Engineering Page 5
MOD 3 Introduction to Python Programming (BPLCK105B)
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.
create a list cats and write shelfFile['cats'] = cats to store the list in shelfFile as a value
associated with the key 'cats' (like in a dictionary). Then we call close() on shelfFile
Just like dictionaries, shelf values have keys() and values() methods that will return list-
like values of the keys and values in the shelf
Since these methods return list-like values instead of true lists, you should pass them to
the list() function to get them in list form
Shelf values don’t have to be opened in read or write mode—they can do both once
opened
5. Explain with example i) isalpha() ii)isalnum() iii)isspace() (6M)
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
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.
isspace() returns True if the string consists only of spaces, tabs, and newlines and is not
blank.
The isX string methods are helpful when you need to validate user input. The isX string
methods are helpful when you need to validate user input
Example
Meghashree, CSE (ICSB) PA College of Engineering Page 6
MOD 3 Introduction to Python Programming (BPLCK105B)
6. Explain the concept of file handling. Also explain reading and writing process with
suitable examples (8M) (IMP)
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.
1. 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
> helloFile = open('C:\\Users\\your_home_folder\\hello.txt')
2. Reading the Contents of File
If you want to read the entire contents of a file as a string value, use the File object’s
read() method
>>> helloContent = helloFile.read()
>>> helloContent
'Hello world!'
Alternatively, you can use the readlines() method to get a list of string values from
the file, one string for each line of text
For example, create a file named sonnet29.txt in the same directory as hello.txt and
write the following text in it:
Meghashree, CSE (ICSB) PA College of Engineering Page 7
MOD 3 Introduction to Python Programming (BPLCK105B)
Ex: Hello, this is the first line.
This is the second line.
And this is the third line.
> >>sonnetFile = open('sonnet29.txt')
>>> sonnetFile.readlines()
Output:
['Hello, this is the first line.\n', 'This is the second line.\n', 'And this is the third line’]
3. Writing to Files
To write content to a file, open it in write mode ('w') or append mode ('a'). Use the
write() method to add content.
1. Write Mode ('w'):
o Overwrites the file’s content if it already exists.
o Creates a new file if it doesn’t exist.
2. Append Mode ('a'):
o Adds content to the end of the file without overwriting the existing content.
o Creates a new file if it doesn’t exist.
3. Example Usage:
# Write mode ('w') - Overwrites file
file = open('example.txt', 'w')
file.write('This is a new file.\n')
file.close()
# Append mode ('a') - Appends to file
file = open('example.txt', 'a')
file.write('Adding more content to the file.\n')
file.close()
7. Explain the concept of file path .Also discuss absolute and relative file path. (6M)
A file has two key properties: a filename (usually written as one word) and a path.
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
Meghashree, CSE (ICSB) PA College of Engineering Page 8
MOD 3 Introduction to Python Programming (BPLCK105B)
Folders can contain files and other folders. For example, project.docx s in the
Documents folder, which is inside the asweigart folder, which is inside the Users folder
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.”
Example on Windows for absolute path: C:\Users\PACE\Documents\example.txt
Example for relative path: If your script and file are in the same folder, use example.txt
8. With code snippet, explain saving variables using the shelve module and pprint Pformat()
functions.
Meghashree, CSE (ICSB) PA College of Engineering Page 9
MOD 3 Introduction to Python Programming (BPLCK105B)
We can save variables in our Python programs to binary shelf files using the shelve module.
This way, our program can restore data to variables from the hard drive. The shelve module
will let us add, Save, and Open features to our program. For example, if we ran a program
and entered some configuration settings, we could save those settings to a shelf file and then
have the program load them the next time it is run.
Example:
>>> import shelve
>>> shelfFile = shelve.open('mydata')
>>> cats = ['Zophie', 'Pooka', 'Simon']
>>> shelfFile['cats'] = cats
>>> shelfFile.close()
Saving Variables with the pprint.pformat () Function:
The pprint.pprint() function will “pretty print” the contents of a list or dictionary to the
screen, while the pprint.pformat() function will return this same text as a string instead of
printing it. Not only is this string formatted to be easy to read, but 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 .py file. This file will be your very own module that you can import whenever
you want to use the variable stored in it.
Example
>>> import pprint
>>> cats = [{'name': 'Zophie', 'desc': 'chubby'}, {'name': 'Pooka', 'desc': 'fluffy'}]
>>> pprint.pformat(cats)
"[{'desc': 'chubby', 'name': 'Zophie'}, {'desc': 'fluffy', 'name': 'Pooka'}]"
9. What is difference between OS and OS.path modules? Discuss the following 4 methods
of OS module:
Meghashree, CSE (ICSB) PA College of Engineering Page 10
MOD 3 Introduction to Python Programming (BPLCK105B)
i)chdir( ) ii)listdir() iii) getcwd()
OS module OS.path module
The OS module in Python provides functions OS.path module contains some useful
for interacting with the operating system functions on pathnames. The path
parameters are either strings or bytes.
OS comes under Python’s standard utility These functions here are used for different
modules purposes such as for merging, normalizing
and retrieving path names in python
i)chdir
When we change the current working directory to C:\Windows, project.docx is
interpreted as C:\Windows\project.docx.
Python will display an error if you try to change to a directory that does not exist
Example:
>>> os.chdir('C:\\Windows\\System32')
>>> os.getcwd()
'C:\\Windows\\System32'
ii)listdir()
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.)
>>> os.listdir('C:\\Windows\\System32')
['0409', '12520437.cpx', '12520850.cpx', '5U877.ax', 'aaclient.dll', --snip-- 'xwtpdui.dll',
'xwtpw32.dll', 'zh-CN', 'zh-HK', 'zh-TW', 'zipfldr.dll']
iii) ) getcwd()
Every program that runs on your computer has a current working directory, or cwd
can get the current working directory as a string value with the os.getcwd()
>>> import os
>>> os.getcwd ()
'C: \\Python34'
Meghashree, CSE (ICSB) PA College of Engineering Page 11
MOD 3 Introduction to Python Programming (BPLCK105B)
10. Explain different clipboard functions in python used in wiki markup.
Some of the commonly used clipboard functions in Python for wiki markup are:
pyperclip.copy (text) - This function copies the text argument to the clipboard. For
example, pyperclip.copy ('hello world') will copy the string "hello world" to the clipboard
pyperclip.paste () - This function returns the text currently on the clipboard. For example,
my_text = pyperclip.paste() will retrieve the text currently on the clipboard and store it in
the variable my_text
11. Explain how to read specific lines from a file? illustrate with python program
To read specific lines from a file in Python, you can use the readlines()method to read all
the lines into a list, and then access the specific lines you need using list indexing. Here's
an example program that demonstrates how to do this:
12. Explain any five built-in methods available for working with string along methods a with
example.
Meghashree, CSE (ICSB) PA College of Engineering Page 12
MOD 3 Introduction to Python Programming (BPLCK105B)
String Literals in Python
1. Using Double Quotes:
Double quotes allow the use of single quotes inside strings without escaping.
Example:
print ("Python's syntax is user-friendly.")
Output:
Python's syntax is user-friendly.
2. Escape Characters:
Escape characters allow both single and double quotes in the same string.
Example:
print("Python\'s syntax allows for \"complex\" usage.")
Output:
Python's syntax allows for "complex" usage.
3. Raw Strings:
Raw strings (r) prevent escape sequences from being processed.
Example:
print(r"C:\new_folder\test")
Output:
C:\new_folder\test
4. Multiline Strings with Triple Quotes:
Multiline strings are enclosed in triple quotes. Tabs, newlines, and quotes are
preserved.
Example:
long_string = """This is
a multiline
string."""
Meghashree, CSE (ICSB) PA College of Engineering Page 13
MOD 3 Introduction to Python Programming (BPLCK105B)
print(long_string)
Output:
This is
a multiline
string.
5. Indexing and Slicing Strings:
Strings can be indexed or sliced, similar to lists.
Example:
text = "Hello world!"
print(text[0]) # Indexing: First character
print(text[0:5]) # Slicing: First 5 characters
Output:
H
Hello
6. in and not in Operators:
Use in and not in to check the presence of substrings.
Example:
Meghashree, CSE (ICSB) PA College of Engineering Page 14