Python for Data Science: Laboratory Programs in Python

Python Programs using strings and files

Laboratory Programs in Python

Python for Data Science: Laboratory Programs in Python : Functions and Files : Python Programs using strings and files

Python Programming examples based on string


Ex 1 ‒ Traversing a string using while string.

In [4]: msg = 'GoodBye'

index = 0

while index < len(msg):

    letter = msg[index]

    print(letter)

    index = index + 1

G

o

o

d

B

y

e



Ex 2 ‒ The string can be traversed using for loop.

msg = 'GoodBye'

for index in range(0, len(msg)):

letter = msg[index]

print(letter)

index index + 1

Output

G

o

o

d

B

y

е


Ex:3

Write a program to display a set of strings using range() function.

Solution :

handsets = ['Samsung', 'OPPO', 'OnePlus', 'Apple']

    print("The mobile handsets are...")

for i in range(len(handsets)):

print(handsets[i], end ="")

Output

The mobile handsets are...

Samsung OPPO OnePlus Apple

 

Ex. 4

Write a Python program to find the length of a string.

Solution:

def str_length(str):

len=0

for ch in str:

    len+=1

    return len

print("\t\t Program to find the length of a string")

print("Enter some string: ")

str=input()

print("Length of a string is: ",str_length(str))

Output

Program to find the length of a string

Enter some string:

python

Length of a string is: 6

 

Ex. 5

Write a Python program to count occurrences of each word in given sentence.

Solution:

def count_occur(str):

    data=dict()

    words=str.split()

    for word in words:

        if word in data:

            data[word]+=1

        else:

            data[word]=1

        return data

print("Enter some string: ")

str=input()

print(count_occur(str))

Output

Enter some string :

A big black bear sat on a big black rug

{'A': 1, 'big': 2, 'black': 2, 'bear': 1, 'sat': 1, 'on': 1, 'a': 1, 'rug': 1}

 

Ex. 6

Write a Python program to copy one string to another.

Solution :

print("Enter some string: ")

str1=input()

str2="

for i in range (len(str1)):

    str2=str2+str1[i]

print("The copied string is: ",str2)

Output

Enter some string:

Technical

The copied string is: Technical

 

Ex. 7

Write a Python program to check if a substring is present in the given string or not.

Solution :

print("Enter some string: ")

str1=input()

print("Enter a word: ")

str2=input()

if(str1.find(str2)= = ‒1):

        print("The substring ",str2," is not present in ",str1)

else:

        print("The substring ",str2," is present in ",str1)

Output

Enter some string:

sky blue

Enter a word:

blue

The substring blue is present in sky blue

 

Ex. 8

Write a Python program to count number of digits and letters in a string.

Solution :

print("Enter some string: ")

str=input()

digit_count = 0

letter_count = 0

for i in str:

    if(i.isdigit()):

    digit_count+=1

else:

    letter count+=1

print("Total number of digits in ",str," are ",digit_count)

print("Total number of letters in ",str," are ",letter_count)

Output

Enter some string :

Python123Program

Total number of digits in Python123Program are 3

Total number of letters in Python123Program are 13

 

Ex. 9

Write a Python program to count number of vowels in a string.

Solution :

print("Enter some string: ")

str=input()

vowel_count=0

for i in str:

if((i= ='a' or i= ='e' or i= ='i' or i= ='o' or i= ='u')

or((i= ='A' or i= ='E' or i= ='I' or i= ='0' or i= ='U'))):

    vowel_count + =1

print("Total number of vowels in ",str," are ",vowel_count)

Output

Enter some string:

India

Total number of vowels in India are 3

 

Ex. 10

Write a Python program to check if the string is palindrome or not.

Solution :

print("Enter some string: ")

str=input()

rev_str=reversed(str)

if(list(str)==list(rev_str)):

    print("The string ",str," is palindrome")

else:

    print("The string ",str," is not palindrome")

Output

Enter some string :

madam

The string madam is palindrome

 

Ex. 11

Write a Python program to sort the word in a sentence in an alphabetic order.

Solution :

print("Enter some string: ")

str=input()

words_list=str.split()

words_list.sort()

print("The words in sorted order are...")

for word in words_list:

    print(word)

Output

Enter some string :

I like python program very much

The words in sorted order are...

I

like

much

program

python

very

 

Python Programming examples based on Files

Ex. 1

Write a Python program to read the contents of the file named 'test.txt.

Solution :

ReadFile.py

inf = open('D:\\test.txt','rt')

print(inf.read())

inf.close()

Output

In [10]: import ReadFile

Hello

How are you?

I am fine

Good Bye


Ex. 2

Write a Python program to read and display first two lines of the text file.

Solution :

ReadLineDemo.py

inf = open('D:\\test.txt','rt')

print(inf.readline())

print(inf.readline())

inf.close()

Output

Hello

How are you?

Program explanation: In above program,

1) The file is opened using open statement.

2) The we call readline() statements inside two subsequent print statement. After reading from the file using the readline() method, the control automatically passes to the next line. Hence we call readline() inside the print statement again.

3) Finally we must not forget to close the file using close() method.



Ex. 3

Write a program to display the contents of the file using for loop.

Solution :

DisplayFile.py

inf = open('D:\\test.txt','rt')

for line in inf:

        print(line)

inf.close()

Output

Hello

How are you?

I am fine

Good Bye

India is Wonderful country


Ex. 4

Write a Python program to find the line that starts with the word "This" from the following text which is stored in a file.

Test.txt

This is a Python program

Python is superb.

This is third line of program

this Python program is nice

Solution :

FileDemo1.py

fh=open('d:\\test.txt')

i=0

for line in fh:

    line=line.rstrip()

    if line.find("This')= = ‒1:continue

    print(line)

Output

This is a python program

This is third line of program


Ex. 5

Write a program in Python to split the text line written in the file into words.

Solution :

with open('d:\\test.txt','rt') as inf:

    line=inf.readline()

    word_list=line.split()

    print(word_list)

Output

['This', 'is', 'a', 'python', 'program']


Ex. 6

Write a Python program to write multiple lines to a text file using writelines() method.

Solution :

fo=open('d:\\test.txt', 'wt')

lines=["Welcome to the Python programming\n","It is fun\n",

    "Python is easy\n", "But it is powerful programming language"]

fo.writelines (lines)

fo.close()

Output

Now open the Notepad and open the test.txt file in it. It will be something like this ‒


Ex. 7

Write a Python program to write n number of lines to the file and display all these lines as output.

Solution :

print("How many lines you want to write")

n=int(input())

outFile=open("d:\\test.txt","wt")

for i in range(n):

    print("Enter line")

    line=input()

    outFile.write("\n"+line)

outFile.close()

print("The Contents of the file 'test.txt' are ...")

inFile=open("d:\\test.txt", 'rt')

print(inFile.read())

inFile.close()


Ex. 8

Write a Python program to write the contents in 'one.txt' file. Read these contents and write them to another file named 'two.txt'.

Solution :

print("How many lines you want to write")

n=int(input())

outFile=open("d:\\one.txt", 'wt')

for i in range(n):

    print("Enter line")

    line=input()

    outFile.write("\n"+line)

outFile.close()

inFile=open("d:\\one.txt", 'rt')

outFile=open("d:\\two.txt","wt")

i=0

for i in range(n+1):

    line‒inFile.readline()

    outFile.write("\n"+line)

inFile.close()

outFile.close()

print("The Contents of the file 'two.txt' are...")

inFile=open("d:\\two.txt","rt')

print(inFile.read())

inFile.close()


Ex. 9

How to merge multiple files into a new file using Python.

Solution :

one = two ="'

fp=open('d:\\first.txt','rt')

one = fp.read()

fp=open('d:\\second.txt','rt')

second = fp.read()

one+= "\n"

one+= second

fp = open('d:\\third.txt','wt')

fp.write(one)

fp.close()

Step 1: Create a first.txt file using some text‒editor like Notepad.


Step 2: Create a second.txt file using some text‒editor like Notepad.


Step 3: Now open the third.txt file using some text‒editor. It will be as follows ‒


Python for Data Science: Laboratory Programs in Python : Tag: Computer Programming, Python, Data Science : Laboratory Programs in Python - Python Programs using strings and files


Python for Data Science: Laboratory Programs in Python



Under Subject


Python for Data Science

AD25201 2nd Semester AIDS Dept | 2025 Regulation | 2nd Semester 2025 Regulation


Python for Data Science - Laboratory

AD25201 2nd Semester AIDS Dept | 2025 Regulation | 2nd Semester 2025 Regulation



Related Subjects


English Essentials II

EN25C02 2nd Semester | 2025 Regulation | 2nd Semester 2025 Regulation



Linear Algebra

MA25C02 2nd Semester | 2025 Regulation


Applied Physics (CSIE) II

PH25C03 2nd Semester AIDS, CSE, IT, CSE(CY) Dept | 2025 Regulation | 2nd Semester 2025 Regulation


Digital Principles and Computer Organization

CS25C06 2nd Semester AIDS, CSE, IT, CSE(CY) Dept | 2025 Regulation | 2nd Semester 2025 Regulation


Basic Electrical and Electronics Engineering

EE25C01 2nd Semester | 2025 Regulation | 2nd Semester 2025 Regulation


Python for Data Science

AD25201 2nd Semester AIDS Dept | 2025 Regulation | 2nd Semester 2025 Regulation


Re-Engineering for Innovation

ME25C05 2nd Semester | 2025 Regulation | 2nd Semester 2025 Regulation


Python for Data Science - Laboratory

AD25201 2nd Semester AIDS Dept | 2025 Regulation | 2nd Semester 2025 Regulation