0% found this document useful (0 votes)
6 views4 pages

Python Module 3 Question Bank

The document provides an overview of Python string handling methods, file path concepts, and file operations using the os and shelve modules. It includes examples of various string methods, file reading and writing techniques, and programs to calculate file sizes and sort file contents. Additionally, it covers string validation methods and provides sample code for counting alphabets and checking for palindromes.

Uploaded by

pritibagi123
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)
6 views4 pages

Python Module 3 Question Bank

The document provides an overview of Python string handling methods, file path concepts, and file operations using the os and shelve modules. It includes examples of various string methods, file reading and writing techniques, and programs to calculate file sizes and sort file contents. Additionally, it covers string validation methods and provides sample code for counting alphabets and checking for palindromes.

Uploaded by

pritibagi123
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/ 4

Module 3

1. Explain Python string handling methods with examples: split(),endswith(), ljust(), center(),
lstrip(),join(), startswith(),rjust(),strip(),rstrip().
-----i. join(): The join() method is useful when you have a list of strings that need to be joined
together into a single string value.
Ex: ', '.join(['cats', 'rats', 'bats'])
'cats, rats, bats'
ii. split(): The split() method is called on a string value and returns a list of strings.
Ex: 'My name is Simon'.split()
['My', 'name', 'is', 'Simon']
iii. endswith(),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.
Ex: 'Hello world!'.startswith('Hello')
True
>>> 'Hello world!'.endswith('world!')
True
iv. strip(), rstrip(), lstrip():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
Ex: spam = ' Hello World '
>>>spam.strip()
'Hello World'
>>>spam.lstrip()
'Hello World '
>>>spam.rstrip()
' Hello World'
v. ljust(), rjust(), 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.
Ex: 'Hello World'.rjust(20)
' Hello World'
>>> 'Hello'.ljust(10)
'Hello '
The center() string method works like ljust() and rjust() but centers the text rather than justifying it to
the left or right
Ex: 'Hello'.center(20)
' Hello

2. Explain the concept of file path. Also explain absolute and relative path.
-----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.
It has directories, folders and files.
Ex: c:\users\documents\file.txt
Absolute path: An absolute path, which always begins with the root folder. There are also the dot (.)
folders.
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.
Ex: os.path.abspath('.')
'C:\\Python34'
Relative path():A relative path, which is relative to the program’s current working directory. There
are also thedot-dot (..) folders.
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.
Ex: os.path.relpath('C:\\Windows', 'C:\\')
'Windows'

3. Explain with suitable Python program segments: (i) os.path.basename() (ii)


os.path.join(). iii. os.path.dirname()
-----(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.
Ex:path = 'C:\\Windows\\System32\\calc.exe'
>>>os.path.basename(path)
'calc.exe'
(ii) os.path.join(): os.path.join() will return a string with a file path using the correct path separators.
Ex: import os
>>>os.path.join('usr', 'bin', 'spam')
'usr\\bin\\spam'
iii. os.path.dirname(): Calling os.path.dirname(path) will return a string of everything that comes
before the last slash in the path argument.
Ex:>>>os.path.dirname(path)
'C:\\Windows\\System32'

4. Explain reading and saving python program variables using shelve module with suitable
Python program.
-----You can save variables in your Python programs to binary shelf files using the shelve module.
The shelve module will let you add Save and Open features to your program.
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.
Ex: import shelve
>>>shelfFile = shelve.open('mydata')
>>>cats = ['Zophie', 'Pooka', 'Simon']
>>>shelfFile['cats'] = cats
>>>shelfFile.close()

5. Develop a Python program to read and print the contents of a text file.
----- list1=[]
file=open("D:\\hello1.txt")
var=file.readlines()
print(var)
for i in var:
list1.append(i.strip())
print(list1)
list1.sort()
print(list1)
file.close()
file1=open("D:\\hello2.txt",'w')
for i in list1:
file1.write(i+'\n')
file1.close()

Output:
['vidya\n', 'anugna\n', 'shruthi\n', 'bindu\n']
Hello1.txt:['vidya', 'anugna', 'shruthi', 'bindu']
Hello2.txt:['anugna', 'bindu', 'shruthi', 'vidya'

6. Develop a Python program find the total size of all the files in the given.
-----Calling os.path.getsize(path) will return the size in bytes of the file in the path argument.
Program:
totalSize = 0
for filename in os.listdir('C:\\Windows\\System32'):
totalSize = totalSize + os.path.getsize(os.path.join('C:\\Windows\\System32', filename))
print(totalSize)

7. Develop a program to sort the contents of a text file and write the sorted contents into a
separate text file.
----- list1=[]
file=open("D:\\hello1.txt")
var=file.readlines()
print(var)
for i in var:
list1.append(i.strip())
print(list1)
list1.sort()
print(list1)
file.close()
file1=open("D:\\hello2.txt",'w')
for i in list1:
file1.write(i+'\n')
file1.close()
Output:
['vidya\n', 'anugna\n', 'shruthi\n', 'bindu\n']
Hello1.txt:['vidya', 'anugna', 'shruthi', 'bindu']
Hello2.txt:['anugna', 'bindu', 'shruthi', 'vidya']

8. Explain with example isalpha(), isalnum(), isspace(), isdecimal(), isupper(), islower().


-----(i). isupper(), islower():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.
Ex: spam = 'Hello world!'
>>>spam.islower()
False
>>> 'HELLO'.isupper()
True
ii. isalpha(): isalpha() returns True if the string consists only of letters and is not blank.
> 'hello'.isalpha()
True
>>> 'hello123'.isalpha()
False
iii. isalnum(): isalnum() returns True if the string consists only of letters and numbers and is not
blank.
'hello123'.isalnum()
True
iv. isdecimal():isdecimal() returns True if the string consists only of numeric characters and is not
blank.
'123'.isdecimal()
True
v. isspace(): returns True if the string consists only of spaces, tabs, and newlines and is not blank.
>>> ' '.isspace()
True
vi. istitle(): istitle() returns True if the string consists only of words that begin with an uppercase letter
followed by only lowercase letters.
>>> 'This Is Title Case'.istitle()
True

9. Write a program to accept string and display total number of alphabets.


-----defcount_alphabets(input_string):
alphabet_count = 0
for char in input_string:
ifchar.isalpha(): # check if the character is alphabetic
alphabet_count += 1
returnalphabet_count
input_string = input("Enter a string: ")
num_alphabets = count_alphabets(input_string)
print(f"Total number of alphabets in the string: {num_alphabets}")

10. Develop a python code to determine whether give string is a palindrome or not.
-----def isPalindrome(s):
return s == s[::-1]
s = "malayalam"
ans = isPalindrome(s)
if ans:
print("Yes")
else:
print("No")

You might also like