0% found this document useful (0 votes)
23 views5 pages

Module 3 Important Questions With Answers

The document explains various Python string handling methods such as split(), endswith(), center(), lstrip(), join(), startswith(), rjust(), strip(), and rstrip(), providing examples for each. It also covers file system paths, the use of the shelve module for saving and reading variables, and how to read specific lines from a file with Python programs. Additionally, it includes sample programs for determining file sizes and checking if a string is a palindrome.

Uploaded by

WOLFIE
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)
23 views5 pages

Module 3 Important Questions With Answers

The document explains various Python string handling methods such as split(), endswith(), center(), lstrip(), join(), startswith(), rjust(), strip(), and rstrip(), providing examples for each. It also covers file system paths, the use of the shelve module for saving and reading variables, and how to read specific lines from a file with Python programs. Additionally, it includes sample programs for determining file sizes and checking if a string is a palindrome.

Uploaded by

WOLFIE
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
You are on page 1/ 5

Module-3 1.

Explain Python string handling methods with examples: split(),


endswith(), center(), lstrip().
Manipulating Strings & Reading and Writing Files split():
Split method called on a string value and returns a list of strings. The split()
1. Explain Python string handling methods with examples: split(),endswith(), center(),
method splits a string into a list.
lstrip() >>> 'My name is Simon'.split()
['My', 'name', 'is', 'Simon']
2. Explain Python string handling methods with examples: join(), By default, the string 'My name is Simon' is split wherever whitespace
startswith(),rjust(),strip(),rstrip() characters such as the space, tab, or newline characters are found. These
whitespace characters are not included in the strings in the returned list.
3. Explain with examples the isX String Methods.
For example
4. Explain all the useful String Methods >>> 'MyABCnameABCisABCSimon'.split('ABC')
['My', 'name', 'is', 'Simon']
5. Explain with suitable Python program segments: (i) os.path.basename() (ii) os.path.join() >>> 'My name is Simon'.split('m')
['My na', 'e is Si', 'on']
6. Discuss different paths of file system.

7. Explain reading and saving python program variables using shelve module with suitable
endswith():
Python program. endswith() methods return True if the string value they are called ends with
the string passed to the method; otherwise, they return False.
8. Explain how to read specific lines from a file? Illustrate with python Program. >>> 'Hello world!'.endswith('world!')
True
>>> 'abc123'.endswith('12')
False
Programs >>> 'Hello world!'.endswith('Hello world!')
True
1. Develop a Python program find the total size of all the files in the given directory.

2. Develop a python program to determine whether the given string is a palindrome or center():
not a palindrome. The center() string method works like ljust() and rjust() but centers the text
rather than justifying it to the left or right.
3. Develop a Python program to read and print the contents of a text file. >>> 'Hello'.center(20)
' Hello '
>>> 'Hello'.center(20, '=')
'=======Hello========'
lstrip():
The lstrip() method will remove whitespace characters from the right ends,
respectively.
spam = ' Hello World '
>>> spam.lstrip() strip():
'Hello World ' 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()
2. Explain Python string handling methods with examples: join(), string method will return a new string without any whitespace characters at
startswith(),rjust(),strip(),rstrip() the beginning or end.
>>> spam = ' Hello World '
join():
>>> spam.strip()
The join() method is useful when you have a list of strings that need to be 'Hello World'
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 rstrip():
is the concatenation of each string in the passed-in list. For example The rstrip() methods will remove whitespace characters from the left ends,
>>> ', '.join(['cats', 'rats', 'bats']) respectively.
'cats, rats, bats' >>> spam = ' Hello World '
>>> ' '.join(['My', 'name', 'is', 'Simon']) >>> spam.rstrip()
'My name is Simon' ' Hello World'

3. Explain with examples the isX String Methods.


startswith():
The startswith() method return True if the string value they are called on Along with islower() and isupper(), there are several string methods that
begins with the string passed to the method; otherwise, they return False. have names beginning with the word is. These methods return a Boolean
>>> 'Hello world!'.startswith('Hello') value that describes the nature of the string. Here are some common isX
True string methods:
>>> 'abc123'.startswith('abcdef')
False • isalpha(): returns True if the string consists only of letters and is not blank.
>>> 'Hello world!'.startswith('Hello world!') • isalnum(): returns True if the string consists only of letters and numbers
True and is not blank.
• isdecimal(): returns True if the string consists only of numeric characters
rjust(): and is not blank
The rjust() string method return a padded version of the string they are called • isspace(): returns True if the string consists only of spaces, tabs, and
on, with spaces inserted to justify the text. The first argument is an integer newlines
length for the justified string. and is not blank.
>>> 'Hello'.rjust(10) • istitle(): returns True if the string consists only of words that begin with
' Hello' an uppercase letter followed by only lowercase letters.
>>> 'Hello'.rjust(20)
' Hello'
>>> 'hello'.isalpha() False
True >>> 'HELLO'.isupper()
>>> 'hello123'.isalpha() True
False >>> 'abc12345'.islower()
>>> 'hello123'.isalnum() True
True >>> '12345'.isupper()
>>> '123'.isdecimal() False
True
>>> ' '.isspace() 5. Explain with suitable Python program segments: (i) os.path.basename()
True (ii) os.path.join()
>>> 'This Is Title Case'.istitle() i) os.path.basename()
True Calling os.path.basename(path) will return a string of everything that comes
>>> 'This Is not Title Case'.istitle() after the last slash in the path argument. The dir name and base name of a path
False are outlined in Figure.
>>> 'This Is NOT Title Case Either'.istitle()
False

4. Explain all the useful String Methods.


Several string methods analyze strings or create transformed string values.
The upper(), lower(), isupper(), and islower() String Methods
The upper() and lower() string methods return a new string where all the For example
letters in the original string have been converted to uppercase or lowercase, >>> path = 'C:\\Windows\\System32\\calc.exe'
respectively. Nonletter characters in the string remain unchanged. >>> os.path.basename(path)
>>> spam = 'Hello world!' 'calc.exe'
>>> spam = spam.upper()
>>> spam (ii) os.path.join()
On Windows, paths are written using backslashes (\) as the separator between
'HELLO WORLD!'
folder names. OS X and Linux, however, use the forward slash (/) as their path
>>> spam = spam.lower()
separator. If you want your programs to work on all operating systems, you
>>> spam
will have to write your Python scripts to handle both cases.
'hello world!'
Fortunately, this is simple to do with the os.path.join() function. If you pass it
The isupper() and islower() methods will return a Boolean True value if the string values of individual file and folder names in your path, os.path.join()
the string has at least one letter and all the letters are uppercase or lowercase, will return a string with a file path using the correct path separators.
respectively. Otherwise, the method returns False. >>> import os
>>> os.path.join('usr', 'bin', 'spam')
>>> spam = 'Hello world!' 'usr\\bin\\spam'
>>> spam.islower()
6. Discuss different paths of file system. 7. Explain reading and saving python program variables using shelve
Absolute and Relative Paths module with suitable Python program.
There are two ways to specify a file path. You can save variables in your Python programs to binary shelf files using the
• An absolute path, which always begins with the root folder shelve module. This way, your program can restore data to variables from the
• A relative path, which is relative to the program’s current working directory 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
There are also the dot (.) and dot-dot (..) folders. These are not real folders but settings, you could save those settings to a shelf file and then have the program
special names that can be used in a path. A single period (“dot”) for a folder load them the next time it is run.
name is shorthand for “this directory.” Two periods (“dot-dot”) means “the
parent folder.” >>> import shelve
Figure is an example of some folders and files. When the current working >>> shelfFile = shelve.open('mydata')
directory is set to C:\bacon, the relative paths for the other folders and files >>> cats = ['Zophie', 'Pooka', 'Simon']
are set as they are in the figure. >>> shelfFile['cats'] = cats
>>> shelfFile.close()

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. You can make changes to the shelf value as if it were a dictionary.
When you’re done, call close() on the shelf value. Here, our shelf value is
stored in shelfFile. We 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.

8. Explain how to read specific lines from a file? Illustrate with python
Program.
Text files are composed of plain text content. Text files are also known as flat
files or plain files. Python provides easy support to read and access the content
within the file. Text files are first opened and then the content is accessed from
it in the order of lines. By default, the line numbers begin with the 0th index.
2. Develop a python program to determine whether the given string is a
palindrome or not a palindrome.

def isPalindrome(s):
return s == s[::-1]
s = "malayalam"
ans = isPalindrome(s)
if ans:
print("Yes")
else:
Program print("No")
file = open('test.txt')
content = file.readlines()
print("tenth line")
print(content[9])
print("first three lines")
print(content[0:3])

Programs
1. Develop a Python program find the total size of all the files in the given
directory.
import os
size = 0
Folderpath = 'C:/Users/Documents/R'
for path, dirs, files in os.walk(Folderpath):
for f in files:
fp = os.path.join(path, f)
size += os.stat(fp).st_size
print("Folder size: " + str(size))

You might also like