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

Python String Methods and File Handling

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)
12 views4 pages

Python String Methods and File Handling

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

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 '
>>>[Link]()
'Hello World'
>>>[Link]()
'Hello World '
>>>[Link]()
' 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\[Link]
Absolute path: An absolute path, which always begins with the root folder. There are also the dot (.)
folders.
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.
Ex: [Link]('.')
'C:\\Python34'
Relative path():A relative path, which is relative to the program’s current working directory. There
are also thedot-dot (..) folders.
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.
Ex: [Link]('C:\\Windows', 'C:\\')
'Windows'

3. Explain with suitable Python program segments: (i) [Link]() (ii)


[Link](). iii. [Link]()
-----(i)[Link](): Calling [Link](path) will return a string of everything that
comes after the last slash in the path argument.
Ex:path = 'C:\\Windows\\System32\\[Link]'
>>>[Link](path)
'[Link]'
(ii) [Link](): [Link]() will return a string with a file path using the correct path separators.
Ex: import os
>>>[Link]('usr', 'bin', 'spam')
'usr\\bin\\spam'
iii. [Link](): Calling [Link](path) will return a string of everything that comes
before the last slash in the path argument.
Ex:>>>[Link](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 [Link]() and pass it
a filename, and then store the returned shelf value in a variable.
Ex: import shelve
>>>shelfFile = [Link]('mydata')
>>>cats = ['Zophie', 'Pooka', 'Simon']
>>>shelfFile['cats'] = cats
>>>[Link]()

5. Develop a Python program to read and print the contents of a text file.
----- list1=[]
file=open("D:\\[Link]")
var=[Link]()
print(var)
for i in var:
[Link]([Link]())
print(list1)
[Link]()
print(list1)
[Link]()
file1=open("D:\\[Link]",'w')
for i in list1:
[Link](i+'\n')
[Link]()

Output:
['vidya\n', 'anugna\n', 'shruthi\n', 'bindu\n']
[Link]:['vidya', 'anugna', 'shruthi', 'bindu']
[Link]:['anugna', 'bindu', 'shruthi', 'vidya'

6. Develop a Python program find the total size of all the files in the given.
-----Calling [Link](path) will return the size in bytes of the file in the path argument.
Program:
totalSize = 0
for filename in [Link]('C:\\Windows\\System32'):
totalSize = totalSize + [Link]([Link]('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:\\[Link]")
var=[Link]()
print(var)
for i in var:
[Link]([Link]())
print(list1)
[Link]()
print(list1)
[Link]()
file1=open("D:\\[Link]",'w')
for i in list1:
[Link](i+'\n')
[Link]()
Output:
['vidya\n', 'anugna\n', 'shruthi\n', 'bindu\n']
[Link]:['vidya', 'anugna', 'shruthi', 'bindu']
[Link]:['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!'
>>>[Link]()
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:
[Link](): # 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")

Common questions

Powered by AI

The methods os.path.dirname() and os.path.basename() are useful for file path management in Python as they allow developers to extract specific components of a file path. os.path.basename() returns the final component of a path, removing the preceding directory structure, which helps in obtaining just the file name as seen with os.path.basename('C:\Windows\System32\calc.exe'), resulting in 'calc.exe' . On the other hand, os.path.dirname() provides the complementary functionality by returning everything before the last slash, effectively getting the directory path, as in os.path.dirname('C:\Windows\System32\calc.exe'), which returns 'C:\Windows\System32' . These methods facilitate the separation and retrieval of file path components, enhancing file management capabilities .

The 'split()' method in Python is used to divide a string into a list, separating the string at each occurrence of a specified separator (whitespace by default). This aids in text parsing and manipulation. For instance, using 'My name is Simon'.split() would result in the list ['My', 'name', 'is', 'Simon'], effectively segmenting the string by each space . Such utility proves beneficial in processing and analyzing text data, allowing for easier handling of substrings .

Key differences among these string methods are as follows: isalpha() returns True if the string contains only alphabetic characters with no blanks, while isalnum() checks for letters and digits without any blanks . isspace() confirms if the string solely consists of whitespace. isdecimal() specifically returns True for numeric-only strings without blank characters. isupper() and islower() check if a string contains only uppercase or lowercase letters respectively, but require at least one letter in the string . istitle() verifies if each word in the string starts with an uppercase letter, followed by lowercase letters . These methods provide varied and specific checks on string content depending on the criteria .

To implement reading and writing operations simultaneously, you could first read from an input file, process the data as needed (such as sorting), then write the results to a new file. This can be seen in a Python example: open the file with open("D:\hello1.txt") as file: var = file.readlines(); list1 = [i.strip() for i in var]; list1.sort(); with open("D:\hello2.txt", 'w') as file1: for i in list1: file1.write(i+'\n'). This approach enables efficient data manipulation, storing results directly into an output file after processing .

An absolute path specifies a complete path from the root directory to the target file or directory, always beginning with the root folder, allowing for absolute referencing in a file system, such as 'C:\users\documents\file.txt'. Conversely, a relative path specifies the location of a file relative to the current working directory of the program, often starting with '.' representing the current directory or '..' representing the parent directory, such as os.path.relpath('C:\Windows', 'C:\') which returns 'Windows' .

The 'shelve' module in Python allows for the persistent storage of Python program variables by saving them to binary shelf files, functioning similarly to a persistent dictionary. To use it, you open a shelf file using shelve.open() and store variables like lists into it, as demonstrated: import shelve; shelfFile = shelve.open('mydata'); cats = ['Zophie', 'Pooka', 'Simon']; shelfFile['cats'] = cats; shelfFile.close(). This saves the list under the key 'cats', and you can later retrieve them, providing simple save and retrieve functionalities .

To determine if a given string is a palindrome in Python, you can check if the string is equal to its reverse. This can be achieved with a simple function: def isPalindrome(s): return s == s[::-1]. By calling isPalindrome(s) where s is the string, it returns True if the string reads the same backward as forward, as demonstrated with s = "malayalam", which evaluates to True . This concise method leverages Python's slicing ability to reverse strings effectively .

The primary purpose of the 'join()' method in Python is to concatenate a list of strings into a single string, with each element separated by the specified string on which 'join()' is called. For example, if you have a list ['cats', 'rats', 'bats'] and you call ', '.join(['cats', 'rats', 'bats']), the result will be a single string 'cats, rats, bats' .

To sort data from one text file and save the sorted results to another, you can read the content, process it to remove any trailing whitespace, sort it, and then write the sorted data to a new file. This process is demonstrated through a Python program: list1 = []; file = open("D:\hello1.txt"); var = file.readlines(); for i in var: list1.append(i.strip()); list1.sort(); file = open("D:\hello2.txt",'w'); for i in list1: file.write(i+'\n'); file.close(). Here, contents from 'hello1.txt' are stripped of newline characters, sorted, and written to 'hello2.txt' .

The os.path.getsize() method in Python returns the size of the specified file in bytes, which is useful for evaluating the storage space used by a file or calculating total storage usage of a directory. An example scenario includes summing file sizes within a directory to understand storage usage: totalSize = 0; for filename in os.listdir('C:\Windows\System32'): totalSize += os.path.getsize(os.path.join('C:\Windows\System32', filename)); print(totalSize). This usage is particularly beneficial in file system management and disk space optimization tasks .

You might also like