Naincy Mod 3 Python
Naincy Mod 3 Python
Section :- B
__________________________________________________________
=",len(a))
Output :-
Explanation :-
Program :-
a=input("Enter a
for b in range(97,123):
c=0 for
in e:
if(d== chr(b))
character",chr(b),"=",c)
Output :-
Frequency of character e = 1
Frequency of character g = 2
Frequency of character l = 1
Frequency of character o = 2
Explanation :-
A string is accepted from the user & then converted to lowercase & stored
in variable ‘e’.
A for loop is executed from 97 to 123. Within the loop, variable ‘c’ is
initialized with 0.
Another for loop is executed on string ‘e’. If the character of ASCII value of ‘b’
matches the current value of ‘d’, then the value of ‘c’ is increased by 1. If the
value of ‘c’ is greater than 1, then it is displayed.
3) Write a Python program to get a string made of the first 2 and last 2 characters
of a given string. If the string length is less than 2, return the empty string
instead.
Program :- a=input("Enter
=",a[0:2:]+a[len(a)-2:len(a):])
Output :-
Enter a string :- wsresource Required String = wsce
Explanation :- A string is accepted from the user in variable
‘a’.
If the length of the string is less than 2, the message “Empty String” is
displayed.
Else, the first & last 2 characters of the string is sliced & displayed after
concatenation.
4) Write a Python program to get a string from a given string where all
occurrences of its first char have been changed to ‘$’, except the first char itself.
Program :-
a=input("Enter a
in range(1,len(a)):
if(a[0]==a[b]):
s=s+'$'
String is =",s)
Output :-
Explanation :-
A string is accepted from the user. The first character of it is copied onto
variable ‘s’.
A for loop is executed from the 2nd index position to the end of the string. If
the first character of the string matches the character of the current index of
variable ‘b’, then a ‘$’ sign is concatenated to the string ‘s’. Otherwise, the
original character is concatenated with the string ‘s’. The string obtained at the
very end is then displayed.
5) Write a Python program to get a single string from two given strings,
separated by a space and swap the first two characters of each string.
Program :- a=input("Enter
:- ") s=b[:2:]+a[2::]+'
'+a[:2:]+b[2::] print("New
String is =",s)
Output :-
Enter first string :- python Enter
Explanation :- Two strings are accepted from the user in variables ‘a’ & ‘b’
respectively.
6) Write a Python program to add ‘ing’ at the end of a given string (length
should be at least 3). If the given string already ends with ‘ing’, add ‘ly’
instead. If the string length of the given string is less than 3, leave it
unchanged.
is =",a) else:
if(a.endswith("ing")):
a=a+'ly' else:
a=a+'ing'
print("Required String is
=",a)
Output :-
Explanation :-
A string is accepted from the user in variable ‘a’. If the length of the string
is less than 3, then it is displayed without any change.
If the string ends with ‘ing’, then ‘ly’ is concatenated with the given string.
Otherwise, ‘ing’ is concatenated with the given string. The new string obtained
is then displayed.
7) Write a Python program to find the first appearance of the substrings ‘not’ and
‘poor’ in a given string. If ‘not’ follows ‘poor’, replace the whole ‘not’…’poor’
substring with ‘good’. Return the resulting string.
Program :-
c=a[b::].index("poor")
d=a.replace(a[b:c+4+b:], "good")
Output :-
‘a’.
If both the words ‘not’ & ‘poor’ are present in the string, then the index of the
2 words are stored in variables ‘b’ & ‘c’. A new string is created by replacing
the substring (not…poor) using the indexes of ‘not’ & ‘poor’ and the same is
not.
If both the words ‘not’ & ‘poor’ are not present in the string, the same string is
displayed.
8) Write a Python function that takes a list of words and return the longest
word and the length of the longest one. Program :- n=int(input("Enter the
a=input("Enter a
Explanation :-
The number of words is accepted from the user. The first word is
accepted from the user in variable ‘a’ & its length is stored in variable
‘c’. The remaining words are accepted from the user inside a for loop.
Whenever the length of a word is more then the word currently in ‘a’, then
the word & the length of the word is copied on variables’d’ & ‘c’ After the
termination of the for loop, the longest word is displayed.
9)Write a Python program to remove the nth index character from a nonempty
string.
Program :-
a=input("Enter a string :-
") b=int(input("Enter an
range(len(a)):
print("The new
String is =",s)
Output :-
Enter an index :- 3
Explanation :-
A string & an index is accepted from the user in variables ‘a’ & ‘b’. A
blank string ‘s’ is declared
A for loop is iterated on string ‘a’. If the value of variable ‘c’ is equal to that of
variable ‘b’, the continue statement is executed. Otherwise, the actual character
is added to the string ‘s’. The new string obtained is then displayed.
10) Write a Python program to change a given string to a new string where the
first and last chars have been exchanged. Program :- a=input("Enter a String :-
in range(1,len(a)-
1):
d=d+a[b]
d=d+a[0]
print("The required
string
=",d)
Output :-
Explanation :-
A string is accepted from the user. A string ‘d’ is created with the last
character of the input string. All the characters of the input string is
concatenated with string ‘d’. After the termination of loop, the first
character of input string is concatenated with the string ‘d’. The final string
obtained in variable ‘d’ is displayed on the screen.
11) Write a Python program to remove characters that have odd index values in
a given string. Program :- b=input("Enter a string :- ") s='' for a in
range(len(b)): if(a%2!=0):
continue s=s+b[a]
is =",s)
Output :-
Explanation :-
A string is accepted from the user in variable ‘b’. A blank string ‘s’ is also
initialized.
A for loop is iterated on the string ‘b’ using the range() function. When the
value of index is an odd number, continue statement is executed. Otherwise, the
character at the particular index is concatenated with string ‘s’. After the
termination of the loop, the string ‘s’ is displayed.
12) Write a Python program to count the occurrences of each world in a given
sentence. Program :-
a=input("Enter a
for d in
b:
if(d==c)
:
b.remove(d)
e+=1 print("Frequency of the word",c,"=",e)
Output :-
Explanation :-
A sentence is accepted from the user in variable ‘a’. Its words are converted
into a list using the split() function.
A for loop is executed on the list ‘b’. Each word is the variable ‘a’ in each
iteration.
The word in ‘a’ is copied onto variable ‘c’. Variable ‘e’ is initialized with 0.
Another for loop is executed on the list ‘b’. If the words in ‘d’ matches those
ones in ‘c’, then the value of e is increased by 1 & that particular word is
remove from the list.
The value of ‘e’ is displayed in each iteration of the outer loop along with the
loop itself.
13) Write a Python script that takes input from the user and displays that input
back in upper and lower cases. Program :- a=input("Enter an input :- ")
print("Upper Case
=",a.upper()) print("Lower
Case =",a.lower())
Output :-
‘a’.
The given string is displayed in both uppercase & lowercase using the
upper() & lower().
a.append(c)
a.sort() print("Output
:- ",end="") for c in
a:
print(c,end=",")
Output :-
Output :- black,green,red,white,
Explanation :-
A sequence of words is accepted from the user in a comma-separated
sequence.
A list ‘b’ is created with the words using the split() function.
An empty list ‘a’ is created.
A for loop is iterated on list ‘b’. If the word in variable ‘c’ is not present in
list ‘a’, then the word is inserted in list ‘a’.
The list ‘a’ is then sorted in ascending order.
The words in list ‘a’ are displayed in a comma-separated sequence.
15) Write a Python function to create an HTML string with tags around the
word(s). Program :- def add_tags(a,b): s='<'+b+'>'+a+'</'+b+'>' return
s x=input("Enter the
string/word :- ")
y=input("Enter the tag name :-
=",add_tags(x,y)) Output :-
string = <i>Python</i>
Explanation :-
A string & a tag name is accepted from the user in variables ‘x’ & ‘y’
respectively.
The function add_tags() is called. Then, x & y are passed onto it.
Within the function, a new string ‘s’ is created in a HTML tag like
format & returned. The HTML string returned from the function is
displayed.
s=x[:(len(x)//2):]+y+x[len(x)//2::] return s
Output :-
Enter a string :- {{}}
The function insert_string_middle() is called & variables ‘a’ & ‘b’ are
passed onto it.
In the function, a string ‘s’ is created wherein the first half of the 1st string, the
2nd string & the second half of the 1st string is concatenated to each other.
The string ‘s’ is returned from the function & is subsequently displayed. 17)
Write a Python function to get a string made of 4 copies of the last two
a=input("Enter a string
:- ") print("Required
String :-",insert_end(a))
Output :-
Explanation :-
18) Write a Python function to get a string made of the first three characters of a
specified string. If the length of the string is less than 3, return the original
b):
if(len(b)<3
):
return b
else: return b[0:3:] a=input("Enter
",first_three(a))
Output :-
Explanation :-
19) Write a Python program to get the last part of a string before a specified
character.
") c=a[::-
1].partition(b) print("Required
String :-
",c[2][::-1])
Output :-
Enter a character :- -
Explanation :-
A string & a character is accepted from the user in variables ‘a’ & ‘b’
respectively.
A tuple ‘b’ is created using the partition() function on the reverse string using
the character ‘b’.
The 3rd element of the tuple is printed in a reverse manner.
20) Write a Python function to reverse a string if its length is a multiple of 4.
1]) else:
print("Original String :-
",a)
Output :-
if(a[b].isupper()):
c+=1 if(c>=2): print("All
",a)
Output :-
Explanation :-
Output :-
Enter a string :- india is great The
is :great india
is
‘a’.
With the help of split() function, the words of the string are inserted in list
‘b’.
The list ‘b’ is sorted in ascending order using the sort() function.
The elements of the list are then displayed using a for loop.
23) Write a Python program to remove a newline in Python.
Output :-
Explanation :-
Output :-
Explanation :-
A string & a specified set of characters is accepted from the user
in variables ‘a’ & ‘b’. It is checked whether the string ‘b’ begins
with string ‘a’ using statrtswith() function. If the above criteria
satisfies, then a relevant message is displayed & vice versa.
c+=chr((ord(d)+b-65)%26+65)
elif(d.islower()): c+=chr((ord(d)+b-
Output :-
Explanation :-
A string and the length of shift is accepted from the user in variables ‘a’ &
‘b’.
A blank string ‘c’ is initialized immediately after input.
A for loop with index variable ‘d’ is iterated on the input string.
When ‘d’ is a whitespace, a whitespace is concatenated with the string ‘c’.
When ‘d’ is an uppercase alphabet, it is shifted by ‘b’ number of times to the
right using a few binary operators & obtaining the ASCII value of the character
in variable ‘d’. When ‘d’ is a lowercase alphabet, the same process is repeated
with minimal changes.
The string obtained in ‘c’ after the termination of the loop is the Caesar
Encryption.
downy
String
:-")
print(textwrap.fill(a,wi dth=50))
Output :-
Original String :- He
Formatted String :-
He gives his harness bells a shake To
27) Write a Python program to remove existing indentation from all of the lines
print(textwrap.dedent(a))
Output :- Original
28) Write a Python program to add prefix text to all of the lines in a string.
Program :- import textwrap a='''He gives his harness bells a shake
print(textwrap.indent(a,'* '))
downy
flake.
mistake.
* The only other sound’s the
flake.
program.
shake
print(textwrap.fill(b,initial_indent='',subsequent_inden
t=' '*4,width=30))
Output :- Original
and downy
flake.
program.
30) Write a Python program to print the following numbers upto 2 decimal
places.
Program :- while(True):
a=float(input("Enter a number :- (0
Explanation :-
While a true while loop, a floating point number is accepted from the user
in variable ‘a’.
If the number entered is 0, break statement is executed & the loop terminates.
The “{:.2f}”.format() statements are used to round off the given number upto 2
decimal places. The number obtained after rounding off is displayed on the
screen.
31) Write a Python program to print the following numbers upto 2 decimal places
with a sign. Program :- while(True): a=float(input("Enter a number
:-
=","{:+.2f}".format(a))
Output :-
a=float(input("Enter a number :- (0
=","{:.0f}".format(a))
Output :-
Explanation :-
While a true while loop, a floating point number is accepted from the user
in variable ‘a’.
If the number entered is 0, break statement is executed & the loop terminates.
The “{:.0f}”.format() statements are used to round off the given number &
return a number without the decimal part. The number obtained after rounding
off is displayed on the screen along with the sign.
33) Write a Python program to print the following integers with zeros to the
Output :-
Output :-
000678
Explanation :-
While a true while loop, a floating point number is accepted from the user in
variable ‘a’.
If the number entered is 0, break statement is executed & the loop terminates.
The format() function generates the number in the required format. The
{:0>6d} specification is used to print the zeroes to the left of the specified
width i.e. 6.
34) Write a Python program to print the following integers with ‘*’ to the right of
the specified width. Program :- while(True): a=int(input("Enter a number
Output :-
539****
Explanation :-
While a true while loop, a floating point number is accepted from the user
in variable ‘a’.
If the number entered is 0, break statement is executed & the loop terminates.
The format() function generates the number in the required format. The
{:*<7d} specification is used to print the zeroes to the left of the specified
width i.e. 7.
print("Required
Output
=",b)
Output :-
print("Formatted Number
=","{:.2%}".format(a))
Output :-
‘a’.
The formatted number is obtained by using the format() function & {:.2%}
specification.
38) Write a Python program to display a number in left, right, and center
aligned with a width of 10.
print("Center Aligned
=","{:^10d}".format(a))
print("Right Aligned
=","{:10d}".format(a))
Output :-
Enter a number :- 43 Width
= 10
Left Aligned = 43
Center Aligned = 43
Right Aligned = 43
Explanation :- A number is accepted from the user in variable ‘a’. The width
is 10.
of Occurrences
=",a.count(b))
Output :-
Enter a substring :- ab
Number of Occurrences = 3
Explanation :-
A string & a substring is accepted from the user in variables ‘a’ & ‘b’
respectively.
The number of occurrences of the substring in the given string is calculated
with the help of the count() function & the same is displayed on the screen.
String :-",a[::-
1])
Output :- Enter a
string :- laptop
Reverse String
:- potpal
Explanation :-
:- ") b=a.split()
print(a[::-1])
Output :- Enter a
are
:aidni
si taerg
Explanation :-
41) Write a Python program to strip a set of characters from a string. Program :-
Explanation :-
A string & a set of characters are accepted from the user in variables ‘a’ &
‘b’.
A new string ‘d’ is created with help of those characters which are present in
the string but not in the specified set of characters using join() function, not in
operator & for loop. The new string obtained is then displayed.
c=0 for d
in e:
if(d==chr(b
)):
c+=1 if(c>1):
print(chr(b),"-
>",c)
Output :-
e > 3 h ->
2 o ->
r-
>
2 t
-
>
2u
->
Explanation :-
Explanation :-
Variables ‘a’,’v’,’d’ are initialized with 1256.66,1254.725,2 respectively.
The area of the rectangle is displayed along with the square symbol using
the format() function & {0:. {1}f}cm\u00b2 specification.
The volume of the cylinder is displayed along with the cube symbol using the
format() function & {0:. {1}f}cm\u00b3 specification.
character",a[b],"position at",b)
Output :-
44) Write a Python program to check whether a string contains all letters of the
range(97,123):
c=0 for d
in b:
if(chr(a)==d
):
c+=1 if(c==0)
:
f=1
break if(f==0)
Output :-
Explanation :-
A string is accepted from user in variable ‘a’. It is converted to lowercase
in string ‘b’. A variable ‘f’ is initialized with 0.
A for loop is iterated from 97 to 122. Within it, variable ‘c’ is initialized
with 0.
An inner for loop is iterated on string ‘b’. If the character in variable ‘d’
equals the character with ASCII value in variable ‘a’, the value of ‘c’ is
increased by 1.
Within the outer for loop, if the value of ‘c’ is 0, the then value of ‘f’ is changed
to 1 & break statement is executed.
At the end of the outer loop, if the value of ‘f’ is 0 the string contains all the
letters of the alphabet otherwise not. A relevant message is displayed
accordingly.
45) Write a Python program to convert a given string into a list of
Output :-
Enter a string :- The quick brown fox jumps over the lazy dog.
The required list of words is :-
‘a’.
Alist of words is created by using the split() function and the same is
displayed.
",b)
Output :-
in a:
if(b==','):
s+='.' elif(b=='.'):
s+=',' else:
s+=b
print("Required
String :-",s)
Output :-
Explanation :-
A string is accepted from the user in variable ‘a’. A blank string ‘s’ is
also declared. A for loop with index variable ‘b’ is iterated on string
‘a’.
In every iteration, if ‘b’ is a dot, then a comma is concatenated with string ‘s’. If
‘b’ is a comma, then a dot is concatenated with string ‘s’. Otherwise, the
original character is concatenated with the string
‘s’.
The new string created after termination of loop is then displayed.
48) Write a Python program to count & display vowels in text. Program :-
b=='O' or b=='U'):
c+=1
Output :-
Enter a string :- laptop The
vowels are
:a o
Number of vowels = 2
Output :-
Enter a delimiter :- ,
is
:red,blue,green yellow
Explanation :-
A string & a delimiter is accepted from the user in variables ‘a’ & ‘b’
respectively.
A tuple is created using the partition() function & the delimiter as the
separator on the input string in a reverse order.
The strings at the 0th & 2nd index position is displayed on the screen in a after
reversing.
51) Write a Python program to find the first non-repeating character in a given
string.
Program :- a=input("Enter a
for d in a: if(b==d):
Output :-
‘a’.
An outer for loop with index variable ‘b’ is iterated on the string ‘a’. Within
its body, variable ‘c’ is initialized with 0.
An inner for loop with index variable ‘d’ is iterated on ‘a’. If the character of
‘d’ matches with the character of ‘b’, the value of ‘c’ is increased by 1. Within
the outer loop, if the value of ‘c’ is equal to 1 , the character in ‘b’ is displayed.
52) Write a Python program to print all permutations with a given repetition
product(c,repeat=b):
print(e)
Output :-
('a', 'a')
('a', 'b')
('a', 'c')
('b', 'a')
('b', 'b')
('b', 'c')
('c', 'a')
('c', 'b')
('c', 'c')
program .
c=0 for d in a:
print("First repeating
Output :-
‘a’.
An outer for loop with index variable ‘b’ is iterated on the string ‘a’. Within
its body, variable ‘c’ is initialized with 0.
An inner for loop with index variable ‘d’ is iterated on ‘a’. If the character of
‘d’ matches with the character of ‘b’, the value of ‘c’ is increased by 1. Within
the outer loop, if the value of ‘c’ is more than 1 , the character in ‘b’ is
displayed.
54) Write a Python program to find the first repeated character in a given
c=0 for
d in
a:
if(b==d)
repeating character:",b)
",a.index(b)) break
Output :-
:- p First occurrence at
index :- 2
‘a’.
An outer for loop with index variable ‘b’ is iterated on the string ‘a’. Within
its body, variable ‘c’ is initialized with 0.
An inner for loop with index variable ‘d’ is iterated on ‘a’. If the character of
‘d’ matches with the character of ‘b’, the value of ‘c’ is increased by 1. Within
the outer loop, if the value of ‘c’ is more than 1 , the character in ‘b’ is
displayed. Also, the first index of the character is displayed using the index()
function.
55) Write a Python program to find the first repeated word in a string.
is :-",a)
break
Output :-
Enter a string :- the more you know the more you grow
Explanation :-
A string is accepted from the user in variable ‘a’. A list is created which
contains all the words of the input string using the split() function.
An outer for loop with index variable ‘b’ is iterated on the list ‘a’. Within its
body, variable ‘c’ is initialized with 0.
An inner for loop with index variable ‘d’ is iterated on list ‘a’. If the
word in ‘d’ matches with the word in ‘b’, the value of ‘c’ is increased by 1.
Within the outer loop, if the value of ‘c’ is more than 1 , the word in ‘b’ is
displayed.
56) Write a Python program to find the second most repeated word in a
given string.
Program :- a=input("Enter
it() for d in c: if d in
b:
b[d]+=
1 else:
b[d]=1 e=sorted(b.items(),key=lambda
=",e[-2])
Output :-
Enter a string :- i felt happy beacuse i saw the others were happy and because i
knew i should feel happy but i wasn't really happy
Explanation :-
A string is accepted from the user in variable ‘a’. A blank dictionary ‘b’ is
also declared.
A list ‘c’ containing all the words of the input string is created using the split()
function.
A for loop with index variable ‘d’ is iterated on list ‘c’. Within it, if the word in
‘d’ is present in the dictionary ‘b’, the value of the current item of the dictionary
is increased by 1 else, 1 is assigned to the current item of the dictionary.
After the termination of the loop, the items of the dictionary are sorted & the
2nd largest item & its corresponding key is displayed using the lambda
function.
",a.replace(" ",""))
Output :-
Explanation :-
",b)
Output :-
a: if b
in d:
d[b]+=
1 else:
d[b]=1 c=max(d,key=d.get)
print("Character with
maximum
A string is accepted from the user in variable ‘a’. A blank dictionary ‘d’ is also
declared.
A for loop with index variable ‘b’ is iterated on the string ‘a’. Within it, if the
word in ‘b’ is present in the dictionary ‘d’, the value of the current item of the
dictionary is increased by 1 else, 1 is assigned to the current item of the
dictionary.
The largest item is predicted using the max() function & the corresponding
key is stored in variable ‘c’ & the same is displayed.
60) Write a Python program to capitalize the first and last letters of each
print("Words with first & last characters capitalized are :-") for a in b:
s='' for c in
range(len(a)): if
c==0 or c==len(a)-1:
s+=a[c].upper(
continue s+=a[c]
print(s)
Output :-
Enter a string :- kolkata the city of joy
KolkatA
ThE
CitY
OF
JoY
Explanation :-
A string is accepted from the user in variable ‘a’. A list ‘b’ is created which
contains all the words of the input string using the split() function.
An outer for loop with index variable ‘a’ is iterated on the list ‘b’. Within
its body, a blank string ‘s’ is declared.
An inner for loop with index variable ‘c’ is iterated throughout the length of the
string ‘a’. When the value of ‘c’ is 0 or 1 less than the length of the string ‘a’,
the character is first converted to uppercase, then concatenated with the string
‘s’.
61) Write a Python program to remove duplicate characters from a given string.
c+=b
print("New
String :-",c)
Output :-
Explanation :-
A string is accepted from the user in variable ‘a’. A blank string ‘c’ is also
created.
A for loop with index variable ‘b’ is iterated on the string ‘a’. If the
character in variable ‘b’ is not present in string ‘c’, the character is
concatenated with the string ‘c’.
The new string obtained after removing duplicate characters is then displayed.
62) Write a Python program to compute the sum of the digits in a given string.
if(b.isdigit()):
c+=int(b) print("Sum of
Digits =",c)
Output :-
Sum of Digits = 35
Explanation :-
A string is accepted from the user in variable ‘a’. Variable ‘c’ is initialized
with 0.
A for loop with index variable ‘b’ is iterated on string ‘a’. If the character
in variable ‘b’ is a digit, then it converted to an integer & the same is added
with variable ‘c’. The value of ‘c’ is the sum of digits in the given string & is
then displayed.
63) Write a Python program to remove leading zeros from an IP address. Program
:-
import re a=input("Enter an
[0]*','.',a)
print("New IP Address
=",b) Output :-
Explanation :-
a given binary string. Program :- a=input("Enter a binary string :- ") f=0 for b
if(b==len(a)):
Output :-
Program :- a=input("Enter
b=input("Enter 2nd
for d in range(97,123):
b: if
chr(d) not in c:
c.append(chr(d))
c.sort()
if
characters") else:
print(c)
Output :-
Explanation :-
Two lowercase strings are accepted from the user in variables ‘a’ &
‘b’ respectively. An empty list ‘c’ is also created.
A for loop with index variable ‘d’ is iterated from 97 to 122 with an increment
of 1.
If the character with the ASCII value of variable ‘d’ is present in both the
strings, then it is further checked whether the character is present in the list ‘c’.
If the character is not present in the list, it is inserted into the list.
After the termination of the for loop, the list is sorted in ascending order.
If the length of the list is 0, "No common characters" message is displayed
otherwise the list is displayed.
66) Write a Python program to make two given strings (lower case, may or may
not be of the same length) anagrams without removing any characters from any
c={} for d
in x:
if d not in c:
c[d]=1 else:
c[d]+=1 return c
def anagram(y,
z):
p=map(y) q=map(z)
e=0
e+=loop(
p,q)
e+=loop(
q,p) return
e def loop(i,j):
f=0 for k in
i.keys(): if k not in j:
f+=i[k] else:
f+=max(0,i[k]-j[k]) return f
=",anagram(a,b)) Output :-
Explanation :-
Two strings are accepted from the user. The anagram() function is called &
both the strings are passed onto it.
Within the anagram function(), the map() function is called twice. The
strings stored in ‘y’ & ‘z’ are passed each time & variables ‘p’ & ‘q’ stores
the dictionaries returned by the map function. A variable ‘e’ is initialized
with 0.
The loop() function is called twice & the dictionaries ‘p’ & ‘q’ are passed
alternatively each time & the values returned by it are added to variable ‘e’.
The value of ‘e’ is returned which marks the end of the anagram() function.
Within the map() function, a blank dictionary ‘c’ is created. A for loop with
index variable ‘d’ is iterated on ‘x’.
Within the body of the loop, it is checked whether ‘d’ is a key of the dictionary.
If yes, the value of the corresponding item is increased by 1. Otherwise, a new
key is created along with its corresponding item, the value of which is set
as
1. After the termination of the loop, the dictionary ‘c’ is returned.
Within the loop() function, a variable ‘f’ is initialized with 0. A for loop with
index variable ‘k’ is iterated on the list containing the keys of dictionary ‘i’. If
the key ‘k’ is not present in dictionary ‘j’, the value of the corresponding item
of dictionary ‘i’ is added to variable ‘f’. Otherwise, the maximum between the
difference of values of items of the two lists is added to variable ‘f’. The value
of ‘f’ is returned.
After the execution of all the functions, the value returned by the anagram()
function is displayed.
itertools import
groupby
a=input("Enter a string
(key,range) in
groupby(a):
b.append(key) print("New
String :-
",''.join(b))
Output :-
Explanation :-
first string, use the characters that occur only once, and for the second, use the
e=0 for f in
a:
if(d==f)
e+=1 if(e==1
):
b+=d elif(e>1
): if d
not in c:
c+=d print("First
String
:-",b) print("Second
String :-",c)
Output :-
Enter a string :- approximately
Second String :- ap
Explanation :-
A string is accepted from the user. Two blank strings namely, ‘b’ & ‘c’ are
created.
A for loop with index variable ‘d’ is iterated on ‘a’. A variable ‘e’ is initialized
with 0.
Another for loop with index variable ‘f’ is iterated on ‘a’. Within its body, it is
checked whether, the character in ‘d’ matches the character in ‘f’. If this
condition satisfies, the value of ‘e’ is increased by 1.
Within the body of the outer loop, if the value of ‘e’ is 1, the character in ‘d’ is
concatenated with string ‘b’. If the value of ‘e’ is more than 1 & if the
character in ‘d’ is not present in string ‘c’, then the character is concatenated
with string ‘c’.
After the termination of the outer loop, both the strings are displayed.
69) Write a Python program to find the longest common sub-string from two
d=c.find_longest_match(0,len(a)
,0,len(b)) if(d.size!=0):
is not present")
Output :-
Explanation :-
70) Write a Python program that concatenates uncommon characters from two
d+=c
created.
A for loop with index variable ‘c’ is iterated on ‘a’. If the character in
variable
‘c’ is absent in both the strings ‘b’ & ‘d’, then the character is concatenated
with string ‘d’.
A for loop with index variable ‘c’ is iterated on ‘b’. If the character in variable
‘c’ is absent in both the strings ‘a’ & ‘d’, then the character is concatenated with
string ‘d’.
After the termination of both the for loops, the resultant string ‘d’ is displayed.
71) Write a Python program to move all spaces to the front of a given
'*d e='"'+e+''.join(b)+'"
Output :-
Explanation :-
") b=input("Enter a
a: if b!=d:
continue c+=d
print("Required
Output :-",c)
Output :-
Enter a string :- google
Enter a character :- g
Required Output :- gg
Explanation :-
A string & a character is accepted from the user in variable ‘a’ & ‘b’
respectively. A blank string ‘c’ is also created.
A for loop with index variable ‘d’ is iterated on the input string. If the
input character is not the current character stored in variable ‘d’, then
continue statement is executed.
The character in variable ‘d’ is concatenated with variable ‘c’.
The new string formed in variable ‘c’ is displayed.
73) Write a Python program to count Uppercase, Lowercase, special
d+=1 else:
s+=1
of
Number of Digits = 4
Explanation :-
74) Write a Python program to find the minimum window in a given string
that will contain all the characters of another given string. Program :- import
collections a=input("Enter 1st string :- ") b=input("Enter 2nd string :- ")
x,y=collections.Counter
(b),len(b)
y-
=x[c]>0 x[c]-=1 if
not y:
x[a[i]]<0:
x[a[i]]+=1
i+=1 if not q or
j-i<=q-p:
p,q=i,j
print("Minimum Window :-
",a[p:q])
Output :-
Explanation :-
1,9999999999
i=defaultdict(lamb da:0)
for j in range(b):
i[a[j]]+=
1 if
i[a[j]]==
1:
e+=1 if
e==c:
while
i[a[f]]>1: if i[a[f]]>1:
i[a[f]]-=1
f+=1
k=jf+1 if
h>k:
h=k
",a[g:g+h])
Output :-
Enter a string :- anaya
Smallest Window :-
nay
Explanation :- The defaultdict module is imported from the
collections package.
A string is accepted from the user in variable ‘a’ & its length is calculated &
stored in variable ‘b’. The number of characters is also counted & stored in
variable ‘c’.
Four variables ‘e’, ‘f’, ‘g’, & ‘h’ are initialized with 0, 0, -1, & 9999999999
respectively.
A dictionary named ‘i’ is created using the defaultdict function.
A for loop with index variable ‘j’ is iterated throughout the length of the string.
The value of the corresponding key of the dictionary is increased by 1. If
the value is 1, the value of ‘e’ is increased by 1.
If the value of ‘e’ matches with the value of ‘c’, then a while loop with the
terminating condition (value of the corresponding key of the dictionary is
greater than 1) is iterated. If the value is greater than 1, it is decreased by 1. The
value of ‘f’ is increased by 1.
A new variable ‘k’ is created by adding the value of ‘j’ with 1 & subtracting
‘f’ from it.
If the value of ‘h’ is greater than ‘k’, the value of ‘k’ & ‘f’ are copied onto ‘h’ &
‘g’.
The smallest window obtained is then displayed.
76) Write a Python program to count the number of substrings from a given
of 'k' :- ")) b=len(a) r=0 c=[0]*27 for i in range(b): d=0 c=[0]*27 for j
in range(i,b):
if(c[ord(a[j])-
97]==0):
d+=1 c[ord(a[j])97]+=1
if(d==k):
r+=1 if(d>k):
:-",r)
Output :-
Explanation :-
A string is accepted from the user in variable ‘a’. Its length is calculated &
stored in ‘b’.
A variable ‘r’ is initialized with 0. A character counted array is also
created.
A for loop is executed throughout the length of the string.
Within an inner for loop, the distinct character count is increased by 1.
The character counter is also increased by 1.
The variable ‘r’ is incremented if there is exactly ‘k’ distinct characters. If the
distinct character count is greater than the value of ‘k’, break statement is
executed.
The value stored in variable ‘r’ is then displayed.
77) Write a Python program to count the number of non-empty substrings of a
given string. Program :- a=input("Enter a string :- ") b=len(a); print("Number of
Output :-
Explanation :-
A string is accepted from the user & its length is calculated & stored in
variable ‘b’.
The number of non-empty substrings is calculated using the n(n+1)/2 formula
& type casting is applied on the result obtained.
78) Write a Python program to count characters at the same position in a given
if(b==ord(a[b])ord('A')) or
(b==ord(a[b])-ord('a')):
c+=1 print("Number of characters
=",c)
Output :-
Number of characters = 3
Explanation :-
A string is accepted from the user in variable ‘a’. A variable ‘c’ is also
initialized with 0.
A for loop is iterated throughout the length of the given string.
Within the loop, if the position matches the ASCII value, ‘c’ is increased by 1.
After the termination of the loop, the value of ‘c’ is displayed.
79) Write a Python program to find the smallest & largest words in a given
string.
Program :-
a=input("Enter a string
:- ") b=a.split()
c=d=b[0]
for a in b: if(len(a)>len(c)):
c=a
if(len(a)<len(d)):
d=a
print("Largest Word
:-",c)
print("Smallest
Word :-",d)
Output :-
Smallest Word :- is
Explanation :-
:- ")
r=0 b=len(a)
for i in range(b):
for j in range(i,b):
if(a[i]==a[j]):
r+=1 print("Number of
Substrings
=",r) Output :-
Number of Substrings = 7
Explanation :-
A string is accepted from the user. A variable ‘b’ is initialized with 0. The
length of the input string is also calculated & the same is stored in variable
‘b’.
Two for loops are iterated to generate every substring in each iteration of
the loops.
Within the inner for loop, if both the ends of the substring generated are same,
the value of ‘r’ in increased by 1.
After the termination of both the loops, the value of ‘r’ is displayed.
81) Write a Python program to determine the index of a given string at which a
certain substring starts. If the substring is not found in the given string return
print("Not Found")
Output :-
Explanation :-
A string & a substring is accepted from the user in variables ‘a’ & ‘b’
respectively.
If the substring is present in the string, then its index is displayed using the
index() function. Otherwise, the message “Not Found” is displayed.
82) Write a Python program to wrap a given string into a paragraph with a
print(textwrap.fill(a,b))
Output :-
Required
Output :Python
is very easy.
Explanation :-
while(x!=0)
:
o=str(x%8)+o x//=8
while(y!=0):
b=str(y%2)+b y//=2
while(z!=0): p=z
%16 if(p>=10):
h=chr(p+55)+h
else:
h=str(p)+h z//=16 print("Decimal\
t",o,"\t",h,"\t\t",b)
Output :-
DecimalOctalHexadecimalBinary
elif(c.islower()):
b+=c.upper()
else:
b+=c
print("New
String :-",b)
Output :-
Explanation :-
A string is accepted from the user in variable ‘a’. An empty string ‘b’ is also
created.
A for loop with index variable ‘c’ is iterated on string ‘a’.
Within the loop, if any character is in uppercase, it is first converted to
lowercase & then concatenated with the string ‘b’. If any character is in
lowercase, it is first converted to uppercase & then concatenated with the string
‘b’.
If any character is not an alphabetic one, it is concatenated with the string ‘b’.
The new string obtained after the termination of the loop is displayed.
Output :-
Explanation :-
A bytearray is accepted from the user using the eval keyword in
the form of a list. A generator expression is used to convert each
byte in the list into a 2-digit hexadecimal representation & the
same is stored in a variable ‘b’.
The Hexadecimal string stored in variable ‘b’ is then displayed.
Program :-
a specified character
:- ") print("Modified
String :-",a.replace(b,""))
Output :-
the user.
A new string is created by deleting the occurrences of the given character
in the input string using the replace() function. The new string is
subsequently displayed.
87) Write a Python program to find the common values that appear in two given
a: if c in b and not c
in s:
is :-",s)
Output :-
Explanation :-
Two strings are accepted from the user in variables ‘a’ & ‘b’.
An empty string ‘s’ is also created.
A for loop with index variable ‘c’ is iterated through each character in the
first string.
If the character is present in the second string and is not already present in the
string ‘s’, then the character is concatenated with the string ‘s’.
The new string obtained after the termination of the loop is the required
intersection.
88) Write a Python program to check whether a given string contains a capital
a=input("Enter a
string :- ") if
len(a)<8:
print("Invalid String")
else:
l=u=n=0 for b in a:
if
b.isupper():
u+=1 elif
b.islower():
l+=1 elif
b.isdigit():
n+=1
if(u>0 and l>0 and n>0):
print("Valid String")
else:
print("Invalid String")
W3resource
Valid String
Explanation :-
A string is accepted from the user. If its length is less than 8, “Invalid
String” message is displayed.
If the length is more than 7, 3 variables namely, ‘l’, ‘u’, & ‘n’ are initialized
with 0. A for loop is iterated through each character of the input string.
If the character is an uppercase character, the value of ‘u’ is increased by 1. If
the character is a lowercase character, the value of ‘l’ is increased by 1. If the
character is a digit, the value of ‘n’ is increased by 1.
If the values of all 3 variables are more than 0, then the string is valid otherwise
not.
or c=='
': b+=c
print("New String
:-",b)
Output :-
Explanation :-
A string is accepted from the user. An empty string ‘b’ is also created.
A for loop is iterated through each character of the input string.
If the character is an alphanumeric one or if it is a whitespace, it is concatenated
with the string ‘b’. The new string obtained after the termination of the loop is
displayed.
90) Write a Python program to remove duplicate words from a given string.
c:
c.append(a) print("New
String :-
",' '.join(c))
Output :-
a[b]=str(a[b]) print("Output
String :-
",','.join(a))
Output :-
Explanation :-
A heterogeneous list of scalars is accepted from the user using the eval
keyword.
A for loop is iterated throughout the length of the string.
Within the loop, every element of the list is converted into a string. All
the strings of the list are joined using comma as a separator.
92) Write a Python program to find string similarity between two given
=",c.ratio())
Output :-
Explanation :-
93) Write a Python program to extract numbers from a given string. Program
print("Tuple of integers
=",b)
Output :-
A hexadecimal color code is accepted from the user at the beginning of the
program.
A generator expression & a for loop is used to convert pair of hexadecimal
digits to integers. The result obtained is converted into a tuple & the same is
displayed.
95) Write a Python program to convert the values of RGB components
to a hexadecimal color code. Program :- a=eval(input("Enter a tuple
containing RGB values :- ")) b=('{:02X}'*3).format(a[0],a[1],a[2])
print("Hexadecimal color code =",b)
Output :-
+","
",a).title().replace(" ","")
b=''.join([a[0].lower(),a[1:]])
print("Camelcase :-",b)
Output :-
Explanation :-
The ‘sub’ function is imported from the ‘re’ module at the beginning of
the program. A string is accepted from the user in variable ‘a’.
First, underscores & hyphens are replaced with whitespaces, then the title()
function is used to capitalize the first letter of each word. After that, the
spaces are removed using the replace() function. The first character is converted
to lowercase. The remaining portion of the string & the first character of the
string (converted to lowercase) is joined using the join() function. The new
string obtained is then displayed.
97) Write a Python program to convert a given string to Snake Case.
Z][a-z]+)',r'\1',sub('([A-
",b)
Output :-
Explanation :-
The ‘sub’ function is imported from the ‘re’ module at the beginning of
the program. A string is accepted from the user in variable ‘a’.
Firstly, the hyphens are replaced with whitespaces, then for title case
conversion regular expression substitutions are applied & after that an
underscore is added between the words. The string obtained in the process is
converted to lowercase. The final string is then displayed.
98) Write a Python program to decapitalize the first letter of a given string.
Output :-
the user.
A new string is formed by changing the first character of the input string to
lowercase & then concatenating it with the rest of the string. The string
obtained is then displayed.
98) Write a Python program to split a multi-line string into a list of lines.
print(a) print("Output :-
",a.split('\n'))
Output :-
Original
String :This
is a multili
ne string.
Output :-
['This', 'is a', 'multiline', 'string.', '']
Explanation :-
A multiline string separated by “\n” is initialized in a variable ‘a’. The
original string is first displayed.
Then a list containing all the lines as its elements is created using the split()
function with ‘\n’ as the delimeter. The list obtained is then displayed.
99) Write a Python program to check whether any word in a given string
c=0 for d in
range(97,123): if
chr(d) in a:
c=a.count(chr(d)
Output :-
Enter a sentence :- The wait is over.
True
String do not contain words with duplicate characters!!!
Explanation :-
A string is accepted from the user. It is converted to lowercase & then its
words are converted into a list using split() function. A variable ‘f’ is also
initialized with 0.
A for loop is iterated on every character in the list. A variable ‘c’ is
initialized with 0.
An inner for loop is iterated from 97 to 122. If the character of the ASCII value
is present in the word, then count() function is applied to find out the number of
occurrences.
If the number of occurrences is more than 1, the value of ‘f’ is changed to 1.
Within the outer for loop, if the value of ‘f’ is more than 1, the loop is
terminated using the break statement.
After the execution of the 2 loops, if the value of ‘f’ is 0, then the string
does not contain words with duplicate characters else it contain words with
duplicate characters. A relevant message is displayed along with “True” or
“False”.
101) Write a Python program to add two strings as if they were numbers
(positive integer values). Return a message if the numbers are strings.
a.isdigit() and
b.isdigit():
c=int(a)+int(b)
print("Sum of",a,"&",b,"is
in input!") Output :-
:- 23 Sum of 34
& 23 is = 57
If both of them contains only digits, the both of them are converted to int &
then they are added & the result obtained is subsequently displayed. Otherwise,
"Error in input!" message is displayed.
p=[",","?",".","!",";",":","","_","'",'"',"(",")","{","}","[","]"] for b in p:
s=a.replace(b,"
") a=s
print("New
String :-",s)
Output :-
103) Write a Python program to replace each character of a word of length five
")
len(b[a])>=5:
b[a]="#"*len(b[ a])
a=" ".join(b)
print("New
String :-",a)
Output :-
Explanation :-
A string is accepted from the user. Its words are converted to a list using
split() function. A for loop is iterated through each & every word of the list ‘b’.
If the length of a word is 5 or more, then the word is replaced by replicating
a ‘#’ symbol the number of times the length of the word.
After the termination of the loop, all the elements of it are converted into a
sentence using the join() function with a whitespace as the separator & the
same is displayed.
104) Write a Python program that capitalizes the first letter & lowercases the
remaining letters in a given string. Program :- a=input("Enter a string :- ")
print("New String :-
",a.title())
Output :-
Enter a string :- dow jones industrial average
program.
The first letter of every word is converted to uppercase & the rest of the
letters are converted to lowercase using the title() function. The new string
obtained is displayed.
105) Write a Python program to extract & display the name from a given email
address.
Program :- a=input("Enter an
email
address :- ")
a in b[0]: if a.isalpha():
c+=a print("Name is
:-",c)
Output :-
Name is :- fullyqualifieddomain
Explanation :- An email address is accepted from the user in variable
‘a’.
Using the partition() function, the username, symbol & the domain are
converted into a tuple with each being its elements respectively. An empty
string ‘c’ is also created. A for loop is iterated through the
username of the email address.
If a character of the username is an alphabetic character, then it is concatenated
with the string ‘c’. The string obtained after the termination of the loop is then
displayed.
a=input("Enter a string
:- ") b=a[0]
for c in a: if
b[len(b)-
1]==c:
continue
b+=c print("New
String :-",b)
Output :-
107) Write a Python program that takes two strings. Count the number of
times each string contains the same three letters at the same index.
Program :- a=input("Enter 1st string :- ") b=input("Enter 2nd string :- ") c=0
for d in range(len(a)-
2):
if
a[d:d+3]==b[d:d
+3]:
c+=1
print("Number of
Number of times = 7
Explanation :-
Two strings are accepted from the user in variables ‘a’ & ‘b’. A variable ‘c’ is
also initialized with 0.
A for loop is iterated through the range of indices upto the third last index. If
the substring of length 3 from both strings at the current index is same, the
value of ‘c’ is increased by 1. After the termination of the loop, the value of ‘c’
is displayed.
108) Write a Python program that takes a string and returns # on both sides of
each element, which are not vowels. Program :- a=input("Enter a string :- ")
b='aeiouAEIOU'
s='' for c in a:
if c not in b:
s+='#'+c+'#'
continue
s+=c print("New
String :-",s)
Output :-
109) Write a Python program that counts the number of leap years within the
range of years. Ranges of years should be accepted as strings.
Program :-
")
c=0 for a in
range(int(b[0]),int(b[2])+
1): if int(a)%4==0:
c+=1
Output :-
Explanation :-
A range of years is accepted from the user in the form of a string in variable
‘a’.
A tuple ‘b’ is created containing the two input years & a hyphen using the
partition() function with the ‘-‘ sign as the separator. A variable ‘c’ is also
initialized with 0.
A for loop is iterated from the lower range of years to the higher range of
years.
If the year if divisible by 4, then the value of ‘c’ is increased by 1.
After the termination of the loop, the value of ‘c’ is displayed on the screen.
110) Write a Python program to insert space before every capital letter appears
in a: if
else: c+=b
print("Output :-
",c)
Output :-
Enter a word :- PythonExercisesPracticeSolution
Explanation :-
A word is accepted from the user in variable ‘a’. An empty string ‘c’ is
also created. A for loop is iterated through every character of the input
string.
If the character is an uppercase character, then a whitespace & the character is
concatenated with the string ‘c’. Otherwise, only the character is concatenated.
After the termination of the for loop, the new string obtained is displayed.
111) Write a Python program that takes a string & replaces all the characters with
96,end=" ")
Output :-
Required Output :-
16 25 20 8 15 14 20 21 20 15 18 9 1 12
Explanation :-
A string is accepted from the user. It is converted to lowercase &
stored in variable ‘b’. A for loop is iterated through every character of
the string ‘b’.
If the character is alphabetic, then the number obtained by subtracting 96 from
the ASCII value of the character is displayed along with a whitespace to end in
the same line.
112) Write a Python program to calculate the sum of two numbers given as
a=input("Enter 1st number string :- ") b=input("Enter 2nd number string :- ")
c='"'+str(int(a)+int(b))+'"' print("Sum
=",c)
Output :-
Sum = "1010"
the user.
Both of them are converted to integers & added. The result obtained is
converted to a string & the same is concatenated with 2 double quotes each
on both the ends.
The result obtained in the process is stored in variable ‘c’ & the same is
displayed.
113) Write a Python program that returns a string sorted alphabetically by the
string/sentence :-
") b=a.split()
".join(b))
Output :-
variable ‘a’.
A list containing all the words of the given string is created using the
split() function. The list created is then sorted using the sort() function.
All the words of the list are joined together to from a string with a whitespace
between them using the join() function.