0% found this document useful (0 votes)
8 views

Text Handling

Uploaded by

trishasag7604
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

Text Handling

Uploaded by

trishasag7604
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 7

Aim: Python programs on Text handling

Description: Python programming can be used to process text data for the requirements in various
textual data analysis.

a) Demonstrate the following functions/methods which operates on strings in Python with suitable
examples: i) len( ) ii) strip( ) iii) rstrip( ) iv) lstrip( ) v) find( ) vi) rfind( ) vii) index( ) viii) rindex() ix)
count( ) x) replace( ) xi) split( ) xii) join( ) xiii) upper( ) xiv) lower( ) xv) swapcase( ) xvi) title( ) xvii)
capitalize( ) xviii) startswith() xix) endswith()

i.len(): We can use len() function to find the number of characters present in the string.

s='Python Programming Lab'


print(len(s))
Output:

22

ii.strip(): Used to remove spaces both sides of the string.

Removing spaces from the string: To remove the blank spaces present at either beginning and end of
the string, we can use the following 3 methods:

1. rstrip() ===>To remove blank spaces present at end of the string (i.e.,right hand side)

2. lstrip()===>To remove blank spaces present at the beginning of the string (i.e.,left hand side)

3. strip() ==>To remove spaces both sides

capital=input("Enter your State Name: ")


scapital=capital.strip()
if scapital=='Maharashtra':
print("Maharashtra ..Mumbai")
elif scapital=='Madras':
print("Madras...Chennai")
elif scapital=="Karnataka":
print("Karnataka...Bangalore")
else:
print("your entered city is invalid")
Output:

Enter your State Name: Madras


Madras...Chennai

Enter your city Name: Ap

your entered city is invalid

iii.rstrip(): Used to remove blank spaces present at end of the string (i.e.,right hand side)
capital=input("Enter your State Name:")
scapital=capital.strip()
if scapital=='Maharashtra':
print("Maharashtra ..Mumbai")
elif scapital=='Madras':
print("Madras...Chennai")
elif scapital=="Karnataka":
print("Karnataka...Bangalore")
else:
print("your entered city is invalid")
Output:
Enter your State Name:Maharashtra
Maharashtra ..Mumbai

iv) lstrip(): Used to remove blank spaces present at the beginning of the string (i.e.,left hand side)

city=input("Enter your city Name:")


scity=city.lstrip()
if scity=='Hyderabad':
print("Hello Hyderbadi..Adab")
elif scity=='Chennai':
print("Hello Madrasi...Vanakkam")
elif scity=="Bangalore":
print("Hello Kannadiga...Shubhodaya")
else:
print("your entered city is invalid")
Output:
Enter your city Name: Chennai
Hello Madrasi...Vanakkam

Finding Substrings:

If you want to find whether the substring is available in the given string or not in Python, we have 4
methods.

For forward direction: 1. find() 2. index()

For backward direction: 1.rfind() 2.rindex()

v) v.find():

Syntax: s.find(substring) (Without Boundary)

Returns index of first occurrence of the given substring. If it is not available then we will get -1

s="Python programming lab computer science department"


print(s.find("computer"))
print(s.find("Electrical"))
print(s.find("e"))
Output :

23
-1
29
vi)rfind():

s="python programming lab computer science department python"


print(s.rfind("computer"))
print(s.rfind("python"))
print(s.rfind("e"))
print(s.rfind("m"))
output:

23
51
47
46

vii) index():

index() method is exactly same as find() method except that if the specified substring is not available
then we will get ValueError

s = 'abbaaaaaaaaaaaaaaaaabbababa'
print(s.index('bb'))
output

viii) rindex():

s = 'abbaaaaaaaaaaaaaaaaabbababa'
print(s.rindex('bb'))
Output:

20

ix) count(): We can find the number of occurrences of substring present in the given string by using
count() method.

Different forms of count() function/method:

1. s.count(substring) ==> It will search through out the string

2. s.count(substring, begin, end) ===> It will search from begin index to end-1 index

s="abcabcabcabcadda"
print(s.count('a')) #6
print(s.count('ab')) #4
print(s.count('a',3,7)) #2
output:

6
4
2

x) replace(): We can repalce a string with another string in python using a library function replace().
Syntax: s.replace(oldstring,newstring)

Here, inside 's', every occurrence of oldstring will be replaced with new string

s="python programming lab computer science department python"


s1=s.replace("python","PYTHON")
print(s1)
OUTPUT:

PYTHON programming lab computer science department PYTHON

xi) split():

We can split the given string according to specified seperator by using split() method.

We can split the given string according to specified seperator in reverse direction by using rsplit()
method.

s="cse-ece-eee"
l=s.split('-')
for x in l:
print(x)
OUTPUT

cse
ece
eee

xii) join(): We can join a group of strings(list or tuple) with respect to the given seperator.

Syntax: s=seperator.join(group of strings)

l=['ENJOY','THE','LITTLE','THINGS']
s=' # '.join(l)
print(s)
OUTPUT:

ENJOY # THE # LITTLE # THINGS

xiii) upper(): Used to convert all characters to upper case in the given string.

xiv) lower(): Used to convert all characters to lower case in the given string.

xv) swapcase(): Used to convert all lower case characters to upper case and all upper case characters to
lower case in the given string.

xvi) title(): Used to convert all characters to title case. (i.e first character in every word should be upper
case and all remaining characters should be in lower case in the given string).

xvii) capitalize(): Only first character will be converted to upper case and all remaining characters can be
converted to lower case
s='do things that Makes you Happy'
print(s.upper())
print(s.lower())
print(s.swapcase())
print(s.title())
print(s.capitalize())
output:

DO THINGS THAT MAKES YOU HAPPY


do things that makes you happy
DO THINGS THAT mAKES YOU hAPPY
Do Things That Makes You Happy
Do things that makes you happy

xviii) startswith(): Used to check the starting of the string.

xix) endswith(): Used to check the ending of the string.

s='do things that Makes you Happy'


print(s.startswith('do'))
print(s.endswith('Happy'))
print(s.endswith('you'))
output:

True
True
False

b) Write a Python Program to display all positions of substring in a given main string.

s=input("Enter main string:")


subs=input("Enter sub string:")
flag=False
pos=-1
n=len(s)
c = 0
while True:
pos=s.find(subs,pos+1,n)
if pos==-1:
break
c = c+1
print("Found at position",pos)
flag=True
if flag==False:
print("Not Found")
print('The number of occurrences : ',c)
output:

Enter main string:ababaacbccbababa


Enter sub string:ab
Found at position 0
Found at position 2
Found at position 11
Found at position 13
The number of occurrences : 4

c) Write a program to use split and join methods in the given string and trace a birthday with a
dictionary data structure

str1=input("Enter date of birth:")


sp=str1.split(".")
bday='/'.join(sp)
d1={"birthday":bday
}
if "birthday" in d1:
print(d1["birthday"])
output:

Enter date of birth:10.08.2000


10/08/2000

d) Write a Regular Expression to represent all 10 digit mobile numbers and Write a Python Program to
check whether the given number is valid mobile number or not?

Rules: 1. Every number should contains exactly 10 digits.

2. The first digit should be 7 or 8 or 9

Regular Expression:

[7-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9] or [7-9][0-9]{9} or [7-9]\d{9}

Program :

import re
s = input('Enter Number :')
m = re.fullmatch('[7-9][0-9]{9}',s)
if m!= None:
print(s,'is valid Mobile number')
else:
print(s,'is not valid Mobile number')
output:

Enter Number :9758946214


9758946214 is valid Mobile number

Enter Number :4789632145


4789632145 is not valid Mobile number

e) Write a Python Program to check whether the given mail id is valid gmail id or not?

import re
s=input("Enter Mail id:")
m=re.fullmatch("\w[a-zA-Z0-9_.]*@gmail[.]com",s)
if m!=None:
print("Valid Mail Id");
else:
print("Invalid Mail id")
output:

Enter Mail id:[email protected]


Valid Mail Id

You might also like