Python Practice Strings1
In this class, We discuss Python Practice Strings1.
For Complete YouTube Video: Click Here
These examples will help the reader to improve their coding skill.
Take the complete placement training and practice tests.
The reader can easily crack any campus placement exam.
Try to solve the questions on your own, then check for a solution.
Q1)
What is the output displayed by the below code?
string="hello how are you learning monkey. learning made easy"
lis=["learning","monkey"]
dictionary={}
for i in lis:
occur=0
lis1=[]
while(True):
x=string.find(i,occur)
if x!=-1:
lis1.append([x,x+len(i)-1])
occur=x+len(i)
else:
break
dictionary.update({i:lis1})
print(dictionary)
In the above program, we are using the find method from the String class.
To know about the find method, click here.
The find method will find the input in the given string from the index position given.
We take the words from the list lis and find the position at which the word is present in the given string.
We are finding the position of the word even multiple occurrences of the word.
The position is maintained in a dictionary.
Output:
{'learning': [[18, 25], [35, 42]], 'monkey': [[27, 32]]}
Q2)
What is the output displayed by the below program?
string="hello how are you learning monkey. learning made easy"
string.replace('.','')
x=string.split()
x.pop()
z=set(x)
w='$'.join(z)
print(w)
In the above program, we are using the method replace.
We are replacing dots with an empty string.
The replace is not affected on the string because strings are not modified in place.
The replace function will return the modified string. We are not taking the modified string.
We are eliminating duplicates and joining the words with the dollar.
Given below is the output displayed by the program.
Output:
learning$hello$you$how$made$are$monkey.
For a detailed explanation of the code, watch the video.