Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
8 views

Naincy Mod 3 Python

Uploaded by

Komalgupta
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

Naincy Mod 3 Python

Uploaded by

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

Name:- Naincy Jaiswal

Roll Number :-22CS011107

Section :- B

Subject:- Programming Practices ll (YCS4101)

Module 3:- STRING

__________________________________________________________

1) Write a Python program to calculate the length of a string. Program

:- a=input("Enter a string :- ") print("Length of the String is

=",len(a))

Output :-

Enter a string :- computer

Length of the String is = 8

Explanation :-

A string is accepted from the user in variable ‘a’.


The length of the string is calculated using the len() function & the same is
displayed.
2) Write a Python program to count the number of characters (character
frequency) in a string.

Program :-

a=input("Enter a

string :- ") e=a.lower()

for b in range(97,123):

c=0 for

in e:

if(d== chr(b))

: c+=1 if(c>0): print("Frequency of

character",chr(b),"=",c)

Output :-

Enter a string :- google

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 string :- ") if(len(a)<2): print("Empty

String") else: print("Required String

=",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

string :- ") s=a[0] for b

in range(1,len(a)):

if(a[0]==a[b]):

s=s+'$'

continue s=s+a[b] print("The new

String is =",s)

Output :-

Enter a string :- restart

The new String is = resta$t

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

first string :- ")

b=input("Enter second string

:- ") s=b[:2:]+a[2::]+'

'+a[:2:]+b[2::] print("New

String is =",s)

Output :-
Enter first string :- python Enter

second string :- java

New String is = jathon pyva

Explanation :- Two strings are accepted from the user in variables ‘a’ & ‘b’

respectively.

A new string ‘s’ is created by concatenating the first 2 characters of the


second string, the first string from 3rd index onwards, followed by a
whitespace, then again concatenating the first 2 characters of the first string, the
second string from 4th index onwards. The new string obtained is then
displayed.

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.

Program :- a=input("Enter a string :- ") if(len(a)<3):


print("Required string

is =",a) else:

if(a.endswith("ing")):

a=a+'ly' else:

a=a+'ing'

print("Required String is

=",a)

Output :-

Enter a string :- string

Required String is = stringly

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 :-

a=input("Enter a string :- ") if('not' in a

and 'poor' in a): b=a.index("not")

c=a[b::].index("poor")

d=a.replace(a[b:c+4+b:], "good")

print("The new string is =",d) else:

print("The unchanged string is =",a)

Output :-

Enter a string :- He is not that poor to take a loan

The new string is = He is good to take a loan

Enter a string :- He is not blind

The unchanged string is = He is not blind

Explanation :- A string is accepted from the user in variable

‘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

number of words :- ")) a=input("Enter a

word :- ") c=len(a) for b in range(n-1):

a=input("Enter a

word :- ") if(len(a)>c): d=a

c=len(a) print("Longest Word =",d)

print("Length of the Longest

Word =",c) Output :-

Enter the number of words :- 3

Enter a word :- run

Enter a word :- laptop

Enter a word :- high

Longest Word = laptop

Length of the Longest Word = 6

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

index :- ")) s='' for c in

range(len(a)):

if(c==b): continue s=s+a[c]

print("The new

String is =",s)

Output :-

Enter a string :- computer

Enter an index :- 3

The new String is = comuter

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 :-

") d=a[len(a)-1] for b

in range(1,len(a)-

1):

d=d+a[b]

d=d+a[0]

print("The required

string

=",d)

Output :-

Enter a String :- python

The required string = nythop

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]

print("The required string

is =",s)

Output :-

Enter a string :- computer

The required string is = cmue

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

sentence :- ") b=a.split()


for a in b: c=a e=0

for d in

b:

if(d==c)

:
b.remove(d)
e+=1 print("Frequency of the word",c,"=",e)

Output :-

Enter a sentence :- My home is sweet home

Frequency of the word My = 1

Frequency of the word is = 1

Frequency of the word home = 2

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 :-

Enter an input :- India is Great

Upper Case = INDIA IS GREAT

Lower Case = india is great

Explanation :- A string is accepted from the user in variable

‘a’.

The given string is displayed in both uppercase & lowercase using the
upper() & lower().

14) Write a Python program that accepts a comma-separated sequence of words


as input and print the distinct words in sorted form (alphabetically).
Program :- a=input("Enter a sequence of words :- ") b=a.split(",") a=[] for c in b:

if(c not in a):

a.append(c)
a.sort() print("Output

:- ",end="") for c in

a:

print(c,end=",")
Output :-

Enter a sequence of words :- red,white,black,red,green,black

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 :-

") print("HTML string

=",add_tags(x,y)) Output :-

Enter the string/word :- Python

Enter the tag name :- i HTML

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.

16) Write a Python function to insert a string in the middle of a string.

Program :- def insert_string_middle(x,y):

s=x[:(len(x)//2):]+y+x[len(x)//2::] return s

a=input("Enter a string :- ") b=input("Enter

the string to be inserted:-

") print("Required String :- ",insert_string_middle(a,b))

Output :-
Enter a string :- {{}}

Enter the string to be inserted:- Python

Required String :- {{Python}}


Explanation :- Two strings are accepted from the user in variables

‘a’ & ‘b’.

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

characters of a specified string (length must be at least. Program :- def

insert_end(b): if(len(b)>=2): c=b[len(b)-2:len(b):]*4 return c

a=input("Enter a string

:- ") print("Required

String :-",insert_end(a))

Output :-

Enter a string :- Python

Required String :- onononon

Explanation :-

A string is accepted from the user in variable ‘a’.


The insert_end() function is called & string ‘a’ is passed onto it. In
the function insert_end(), if the length of the string is greater than 2,
then a new string ‘c’ is created with the last two digits of the string
repeated 4 times. The string ‘c’ is returned & the same is displayed.

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

string. Program :- def first_three(

b):

if(len(b)<3

):
return b
else: return b[0:3:] a=input("Enter

a string :- ") print("Required String :-

",first_three(a))

Output :-

Enter a string :- Python

Required String :- Pyt

Explanation :-

A string is accepted from the user in variable ‘a’.


The function first_three() is called & string ‘a’ is passed onto the function.
Within the function, if length of the string is less than 3, the original string
is returned.
If the length of the string is 3 or more, the first 3 characters are returned. The
string returned is displayed on the screen.

19) Write a Python program to get the last part of a string before a specified
character.

Program :- a=input("Enter a string

:- ") b=input("Enter a character :-

") c=a[::-

1].partition(b) print("Required

String :-
",c[2][::-1])

Output :-

Enter a string :- https://www.w3resource.com/python-exercises/

Enter a character :- -

Required String :- https://www.w3resource.com/python

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.

Program :- a=input("Enter a string :- ") if(len(a)%4==0):

print("Reverse String :-",a[::-

1]) else:

print("Original String :-

",a)

Output :-

Enter a string :- Computer


Reverse String :- retupmoC

Explanation :- A string is accepted from the user in


variable ‘a’.
If the length of the string is a multiple of 4, then the reverse string is
displayed.
If the length of the string is not a multiple of 4, then the original string is
displayed.

21) Write a Python function to convert a given string to all uppercase

if it contains at least 2 uppercase characters in the first 4 characters.

Program :- a=input("Enter a string :- ") c=0 for b in range(4):

if(a[b].isupper()):
c+=1 if(c>=2): print("All

uppercase string :",a.upper())

else: print("Original string :-

",a)

Output :-

Enter a string :- ComPuter

All uppercase string :- COMPUTER

Explanation :-

A string is accepted from the user in variable ‘a’.


A variable ‘c’ is initialized with 0.
A for loop with index variable b is iterated upto 4. If the character at the
bth index position is uppercase, then the value of ‘c’ is increased by 1.
After the termination of the loop, if the value of ‘c’ is more than or equal to 2,
the reverse string is displayed otherwise the original string is displayed.

22) Write a Python program to sort a string lexicographically.

Program :- a=input("Enter a string :- ") b=a.split()

b.sort() print("The string sorted lexicographically

is :-") for a in b: print(a)

Output :-
Enter a string :- india is great The

string sorted lexicographically

is :great india

is

Explanation :- A string is accepted from the user in variable

‘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.

Program :- a="Hello\nWorld\nPyth on\nJava" b=a.replace("\n","

") print("Old String :-",a) print("New String :-",b)

Output :-

Old String :- Hello\nWorld\nPython\nJava

New String :- Hello World Python Java

Explanation :-

A variable ‘a’ is initialized with the string "Hello\nWorld\nPython\nJava”.


All the occurrences of “\n” are replaced by an empty substring.
The resulting string is stored in ‘b’ & the same is displayed along with the old
string.
24) Write a Python program to check whether a string starts with

specified characters. Program :- a=input("Enter a string :- ")

b=input("Enter a specified set of characters :- ") if

a.startswith(b): print("String starts with",b) else:

print("String does not start with",b)

Output :-

Enter a string :- rajasthan


Enter a specified set of characters :- raj

String starts with raj

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.

25) Write a Python program to create a Caesar encryption. Program

:- a=input("Enter a string :- ") b=int(input("Enter the length of

the shift :- ")) c='' for d in a:

if(d==" "): c+=" " elif(d.isupper()):

c+=chr((ord(d)+b-65)%26+65)
elif(d.islower()): c+=chr((ord(d)+b-

97)%26+97) print("Caesar Encryption :-",c)

Output :-

Enter a string :- HELLO

Enter the length of the shift :- 3 Caesar


Encryption :- KHOOR

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.

26) Write a Python program to display formatted text (width=50) as


output.

Program :- import textwrap a='''He gives his harness bells a shake

To ask if there is some mistake.

The only other sound’s the


sweep Of easy wind and

downy

flake.''' print("Original String

:-") print(a) print("Formatted

String

:-")
print(textwrap.fill(a,wi dth=50))

Output :-

Original String :- He

gives his harness bells a

shake To ask if there is

some mistake. The only

other sound’s the sweep

Of easy wind and downy flake.

Formatted String :-
He gives his harness bells a shake To

ask if there is some mistake. The

only other sound’s the sweep

Of easy wind and downy flake.


Explanation :- The textwrap package is imported at the beginning of
the program.
Variable ‘a’ is initialized with a multi-line string. The
original string is displayed.
Then the new formatted string is created using the fill module of the textwrap
package & the same is then displayed.

27) Write a Python program to remove existing indentation from all of the lines

in a given text. Program :-

import textwrap a='''He gives

his harness bells a shake

To ask if there is some mistake.

The only other sound’s the

sweep Of easy wind and

downy flake.''' print("Original

String :-") print(a) print("String

without Indentation :-")

print(textwrap.dedent(a))

Output :- Original

String :- He gives his


harness bells a shake To

ask if there is some

mistake. The only other

sound’s the sweep

Of easy wind and downy flake.


String without

Indentation :He gives his

harness bells a shake

To ask if there is some

mistake. The only other

sound’s the sweep

Of easy wind and downy flake.

Explanation :- The textwrap package is imported at the beginning of


the program.
Variable ‘a’ is initialized with a multi-line string. The
original string is displayed.
Then, the new string without indentation is created using the dedent module of
the textwrap package & the same is then displayed.

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

To ask if there is some mistake.

The only other sound’s the

sweep Of easy wind and

downy flake.''' print("Original

String :-") print(a) print("String

after adding prefix text :-")

print(textwrap.indent(a,'* '))

Output :- Original String :- He

gives his harness bells a shake

To ask if there is some mistake.

The only other sound’s the

sweep Of easy wind and

downy

flake.

String after adding prefix

text :* He gives his

harness bells a shake *

To ask if there is some

mistake.
* The only other sound’s the

sweep * Of easy wind and downy

flake.

Explanation :- The textwrap package is imported at the beginning of the

program.

Variable ‘a’ is initialized with a multi-line string.


The original string is displayed.
A string with prefix in each line is created by using the indent module of the
textwrap function. The new string created is then displayed.
29) Write a Python program to set the indentation of the first line.

Program :- import textwrap a='''He gives his harness bells a

shake

To ask if there is some mistake.


The only other sound’s the sweep Of easy wind and

downy flake.''' print("Original String :-") print(a)

b=textwrap.dedent(a).strip() print("Indentation of the

first line :-")

print(textwrap.fill(b,initial_indent='',subsequent_inden

t=' '*4,width=30))
Output :- Original

String :- He gives his

harness bells a shake

To ask if there is some

mistake. The only other

sound’s the sweep

Of easy wind and downy flake.

Indentation of the first line :-


He gives his harness bells a
shake To

ask if there is some

mistake. The only

other sound’s the

sweep Of easy wind

and downy

flake.

Explanation :- The textwrap package is imported at the beginning of the

program.

Variable ‘a’ is initialized with a multi-line string.


The original string is displayed.
A string ‘b’ is created with indentation removed from all the lines using
dedent module.
The fill module is now used to set the appropriate indentation of the first line &
adjust the other lines’ indentation accordingly. The required string is then
displayed on the screen.

30) Write a Python program to print the following numbers upto 2 decimal
places.

Program :- while(True):

a=float(input("Enter a number :- (0

to exit) ")) if(a==0):

break print("Formatted Number =","{:.2f}".format(a))

Output :- Enter a number :- (0 to exit) 158.8468

Formatted Number = 158.85

Enter a number :- (0 to exit) 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

:-

(0 to exit) ")) if(a==0):

break print("Formatted Number with sign

=","{:+.2f}".format(a))

Output :-

Enter a number :- (0 to exit) 45.675

Formatted Number with sign = +45.67

Enter a number :- (0 to exit) -46.786

Formatted Number with sign = -46.79

Enter a number :- (0 to exit) 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 along with the original sign. The number obtained after
rounding off is displayed on the screen along with the sign.
32) Write a Python program to print the following positive & negative numbers

with no decimal places. Program :- while(True):

a=float(input("Enter a number :- (0

to exit) ")) if(a==0):

break print("Formatted Number without decimal

=","{:.0f}".format(a))

Output :-

Enter a number :- (0 to exit) -45.534

Formatted Number without decimal = -46

Enter a number :- (0 to exit) 54.78

Formatted Number without decimal = 55

Enter a number :- (0 to exit) 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 “{:.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

left of the specified width. Program :- while(True): a=int(input("Enter a


number :- (0 to exit) ")) if(a==0): break print("Required

Output :-

(Width = 6)") print("{:0>6d}".format(a))

Output :-

Enter a number :- (0 to exit) 678

Required Output :- (Width = 6)

000678

Enter a number :- (0 to exit) 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 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

:- (0 to exit) ")) if(a==0):


break print("Required Output :-

(Width = 7)") print("{:*<7d}".format(a))

Output :-

Enter a number :- (0 to exit) 539


Required Output :- (Width = 7)

539****

Enter a number :- (0 to exit) 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 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.

35) Write a Python program to display a number with a comma separator.

Program :- a=int(input("Enter a number :- ")) b=",".join(str(a))

print("Required

Output

=",b)

Output :-

Enter a number :- 32458

Required Output = 3,2,4,5,8

Explanation :- An integer number is accepted from the user in


variable ‘a’.
A string ‘b’ is created using the join() function on the integer (converted to
string) with a comma as the separator.
The new string obtained is the required output and subsequently displayed.

36) Write a Python program to format a number with percentage.

37) Program :- a=float(input("Enter a number :- "))

print("Formatted Number

=","{:.2%}".format(a))

Output :-

Enter a number :- 0.345

Formatted Number = 34.50%

Explanation :- A floating point number is accepted from the user in variable

‘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.

39) Program :- a=int(input("Enter a number :- ")) print("Width = 10")

print("Left Aligned =","{:<10d}".format(a))

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.

To display left aligned, format() function & {:<10d} specification is used.


To display center aligned, format() function & {:^10d} specification is used.
To display right aligned, format() function & {:10d} specification is used.

38) Write a Python program to count occurrences of a

substring in a string. Program :- a=input("Enter a

string :- ") b=input("Enter a substring :- ") print("Number

of Occurrences

=",a.count(b))
Output :-

Enter a string :- abrabadabra

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.

39) Write a Python program to reverse a string.

Program :- a=input("Enter a string :- ") print("Reverse

String :-",a[::-

1])

Output :- Enter a

string :- laptop

Reverse String

:- potpal
Explanation :-

A string is accepted from the user in variable ‘a’.


The string is reversed using string slicing method & the same is displayed.
40) Write a Python program to reverse words in a

string. Program :- a=input("Enter a string

:- ") b=a.split()

print("The reverse words

are :-") for a in b:

print(a[::-1])

Output :- Enter a

string :- india is great

The reverse words

are

:aidni

si taerg

Explanation :-

A string is accepted from the user & stored in variable ‘a’.


All the words of the string are inserted in a list ‘b’ using the split() function.
A for loop with index variable ‘a’ is iterated on list ‘b’.
The reverse of every word is obtained using string slicing method & displayed.

41) Write a Python program to strip a set of characters from a string. Program :-

a=input("Enter a string :- ") b=input("Enter a set of characters :- ") c="".join(d

for d in a if d not in b) print("Required String :-",c)


Output :-

Enter a string :- india is great

Enter a set of characters :- iea

Required String :- nd s grt

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.

41) Write a Python program to count repeated characters in a string.

Program :- a=input("Enter a string :- ") e=a.lower() print("The repeated

characters are as follows :-") for b in range(97,123):

c=0 for d

in e:

if(d==chr(b

)):

c+=1 if(c>1):

print(chr(b),"-

>",c)
Output :-

Enter a string :- thequickbrownfoxjumpsoverthelazydog

The repeated characters are as follows :-

e > 3 h ->

2 o ->

r-

>

2 t
-

>

2u

->

Explanation :-

A string is accepted from the user. It is then converted to lowercase.


A for loop is iterated from 97 to 122. Within it, ‘c’ is initialized with 0. An
inner for loop is iterated on list ‘e’. Within it, if the character in ‘d’ is equal
to the character having the ASCII value of ‘b’, then the value of ‘c’ is
increased by 1.
Within the body of the outer for loop, if the value of ‘c’ is greater than 1, the
value of ‘c’ is displayed along the character itself.
42) Write a Python program to print the square and the cube symbols in the area
of a rectangle and the volume of a cylinder. Program :- a=1256.6

v=1254.7 25 d=2 print("Area of Rectangle =

{0:.{1}f}cm\u00b2".format(a,d)) d=3 print("Volume of

Cylinder = {0:.{1}f}cm\u00b3".format(v,d)) Output :-

Area of Rectangle = 1256.66cm²

Volume of Cylinder = 1254.725cm³

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.

43) Write a Python program to print the index of a character in a string.

Program :- a=input("Enter a string :- ") for b in range(len(a)): print("Current

character",a[b],"position at",b)

Output :-

Enter a string :- computer

Current character c position at 0

Current character o position at 1


Current character m position at 2
Current character p position at 3

Current character u position at 4

Current character t position at 5

Current character e position at 6 Current


character r position at 7 Explanation :-

A string is accepted from the user in variable ‘a’.


A for loop is iterated from 0 to the length of the string.
In every iteration, the current character along with the index is displayed.

44) Write a Python program to check whether a string contains all letters of the

alphabet. Program :- a=input("Enter a string :- ") b=a.lower() f=0 for a in

range(97,123):

c=0 for d

in b:

if(chr(a)==d

):

c+=1 if(c==0)
:
f=1

break if(f==0)

: print("String contains all letters of alphabet")


else: print("String does not contain all letters of
alphabet")

Output :-

Enter a string :- avjkmwvwnaaeboltpu

String does not contain all letters of alphabet

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

words. Program :- a=input("Enter a string :- ") print("The required

list of words is :-") print(a.split())

Output :-

Enter a string :- The quick brown fox jumps over the lazy dog.
The required list of words is :-

['The', 'quick', 'brown', 'fox', 'jumps', 'over', 'the', 'lazy', 'dog.']

Explanation :- A string is accepted from the user in variable

‘a’.

Alist of words is created by using the split() function and the same is
displayed.

46) Write a Python program to lowercase the first n characters in a string

Program :- a=input("Enter a string :- ") n=int(input("Enter the value of n

:- ")) b=a[:n:].lower()+a[n::] print("Required Output :-

",b)

Output :-

Enter a string :- UNIVERSITY

Enter the value of n :- 4

Required Output :- univERSITY


Explanation :-

A string & the value of ‘n’ is accepted from the user.


A new string ‘b’ is created by concatenating the first n characters
(converted to lowercase) & the remaining characters from nth index to the
last. The string ‘b’ is displayed on the string.
47) Write a Python program to swap commas & dots in a string.

Program :- a=input("Enter a string :- ") s='' for b

in a:

if(b==','):

s+='.' elif(b=='.'):

s+=',' else:

s+=b

print("Required

String :-",s)

Output :-

Enter a string :- 32.054,23

Required String :- 32,054.23

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 :-

a=input("Enter a string :- ") print("The vowels are :-") c=0 for b in a:

if(b=='a' or b=='e' or b=='i' or b=='o' or b=='u' or b=='A' or b=='E' or b=='I' or

b=='O' or b=='U'):

c+=1

print(b) print("Number of vowel=",c)

Output :-
Enter a string :- laptop The
vowels are

:a o

Number of vowels = 2

Explanation :- A string is accepted from the user. A variable ‘c’ is


initialized with 0. A for loop with index variable ‘b’ is iterated
on the input string.
If the value of ‘b’ is a vowel, the value of c is increased by 1 & the character is
displayed. After the termination of the loop, the number of vowels is displayed.
50) Write a Python program to split a string on the last occurrence of the
delimiter. Program :- a=input("Enter a string :- ") b=input("Enter a delimiter :- ")
c=a[::1].partition(b) print("The String in split form is :-") print(c[2][::-1])
print(c[0][::-1])

Output :-

Enter a string :- red,blue,green,yellow

Enter a delimiter :- ,

The String in split form

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

string :- ") for b in a: c=0

for d in a: if(b==d):

c+=1 if(c==1): print("First non-repeating

character :-",b) break

Output :-

Enter a string :- passport


First non-repeating character :- a

Explanation :- A string is accepted from the user in variable

‘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

number of characters of a given string. Program :- from itertools import

product a=input("Enter a string :- ") b=int(input("Enter the number of

repetitions :- ")) c=list(a) print("The required permutations are :-") for e in

product(c,repeat=b):
print(e)

Output :-

Enter a string :- abc

Enter the number of repetitions :- 2

The required permutations are :-

('a', 'a')

('a', 'b')
('a', 'c')

('b', 'a')

('b', 'b')

('b', 'c')

('c', 'a')

('c', 'b')

('c', 'c')

Explanation :- The package product is imported at the beginning of the

program .

A string & the number of repetitions is accepted from the user in


variables ‘a’ & ‘b’. The string ‘a’ is converted to a list named ‘c’.
A for loop with index variable ‘e’ is iterated on the product function
which have the list ‘c’ & the value of ‘b’ as its parameters. In every
iteration, the tuple returned by ‘e’ is displayed.
53) Write a Python program to find the first repeated character in a string.
Program :- a=input("Enter a string :- ") for b in a:

c=0 for d in a:

if(b==d): c+=1 if(c>1):

print("First repeating

character :-",b) break

Output :-

Enter a string :- laptop


First repeating character :- p

Explanation :- A string is accepted from the user in variable

‘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

string where the index of the first occurrence is smallest. Program :-

a=input("Enter a string :- ") for b in a:

c=0 for

d in
a:

if(b==d)

c+=1 if(c>1): print("First

repeating character:",b)

print("First occurrence at index :-

",a.index(b)) break

Output :-

Enter a string :- laptop

First repeating character

:- p First occurrence at

index :- 2

Explanation :- A string is accepted from the user in variable

‘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.

Program :- a=input("Enter a string :- ") b=a.split() for a in b: c=0 for d in

b: if(a==d): c+=1 if(c>1): print("First repeated word

is :-",a)

break

Output :-

Enter a string :- the more you know the more you grow

First repeated word is :- the

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

a string :- ") b={} c=a.spl

it() for d in c: if d in

b:

b[d]+=

1 else:

b[d]=1 e=sorted(b.items(),key=lambda

kv:kv[1]) print("2nd most repeated word

=",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

2nd most repeated word = ('happy', 4)

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.

57) Write a Python program to remove spaces from a given string.

Program :- a=input("Enter a string :- ") print("New String :-

",a.replace(" ",""))

Output :-

Enter a string :- Python is very easy

New String :- Pythonisveryeasy

Explanation :-

A string is accepted from the user in variable ‘a’.


All the whitespaces of the string are replaced by an empty character using
replace() function. The new string obtained is subsequently displayed.
58) Write a Python program to move spaces to the front of a given string.

Program :- a=input("Enter a string

:- ") b=' '*a.count(" ")+a.replace("

","") print("Required String :-

",b)
Output :-

Enter a string :- Python is very easy

Required String :- Pythonisveryeasy


Explanation :- A string is accepted from the user in
variable ‘a’.
The number of whitespaces in the string is counted using the count() function.
The whitespaces are removed using the replace() function.
An appropriate string is created by concatenating the whitespaces & the
whitespace removed string. The resulting string is then displayed.

59) Write a Python program to find the maximum number of characters in a


given string.
Program :- a=input("Enter

a string :- ") d={} for b in

a: if b

in d:

d[b]+=
1 else:

d[b]=1 c=max(d,key=d.get)

print("Character with

maximum

frequency =",c) Output :-

Enter a string :- computer with python


Character with maximum frequency = t
Explanation :-

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

word in a given string. Program :- a=input("Enter a string :- ") b=a.split()

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

Words with first & last characters capitalized are :-

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’.

Otherwise, the original character is concatenated with the string.


After the loop terminates, the final string created in ‘s’ is displayed.

61) Write a Python program to remove duplicate characters from a given string.

Program :- a=input("Enter a string :- ") c='' for b in a: if b not in c:

c+=b
print("New

String :-",c)

Output :-

Enter a string :- mathematics

New String :- matheics

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.

Program :- a=input("Enter a string :- ") c=0 for b in a:

if(b.isdigit()):

c+=int(b) print("Sum of

Digits =",c)

Output :-

Enter a string :- Hello2542Python6754

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

IP Address :- ") b=re.sub('\.

[0]*','.',a)

print("New IP Address

=",b) Output :-

Enter an IP Address :- 253.05.067.7.095

New IP Address = 253.5.67.7.95

Explanation :-

The re package is imported at the beginning of the program. An


IP Address is accepted from the user in variable ‘a’.
Using the sub module of the re package, all the leading zeros from the given IP
Address is removed. The new IP Address obtained is stored in variable ‘b’ &
then displayed.
64) Write a Python program to find the maximum length of consecutive 0’s in

a given binary string. Program :- a=input("Enter a binary string :- ") f=0 for b

in range(len(a)): c=0 if(a[b]=='0'): while(a[b]=='0' and b<len(a)):


c+=1 b+=1

if(b==len(a)):

break if(c>f): f=c print("Maximum

length of consecutive 0's =",f)

Output :-

Enter a binary string :- 10100001000


Maximum length of consecutive 0's = 4
Explanation :-
A binary string is accepted from the user. A variable ‘f’ is also initialized
with 0.
A for loop with index variable ‘b’ is iterated on the entire length of the input
string.
Within it, a variable ‘c’ is initialized with 0. If the character in the ‘b’th
index is 0, then a while loop is executed with the checking condition a[b]=0
& the
value of ‘b’ less than the length of the given string. Within the while loop,
both the values of ‘c’ & ‘b’ is increased by 1. If the value of ‘b’ equals the
length of the input string, then break statement is executed.
Within the body of the outer loop, it is checked whether the value of ‘c’ is
greater than the value of ‘f’. If the condition satisfies, the value of ‘c’ is
assigned onto ‘f’.
After the termination of the for loop, the value of ‘f’ is displayed.
65) Write a Python program to find all the common characters in lexicographical
order from two given lower case strings. If there are no similar letters print “No
common characters”.

Program :- a=input("Enter

1st lowercase string :- ")

b=input("Enter 2nd

lowercase string :- ") c=[]

for d in range(97,123):

if chr(d) in a and chr(d) in

b: if

chr(d) not in c:

c.append(chr(d))
c.sort()

if

len(c)= =0: print("No common

characters") else:

print(c)

Output :-

Enter 1st lowercase string :- laptop

Enter 2nd lowercase string :- computer


['o', 'p', 't']

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

of the strings. Program :- def map(x):

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

a=input("Enter 1st lowercase string

:- ") b=input("Enter 2nd

lowercase string :- ") print("Output

=",anagram(a,b)) Output :-

Enter 1st lowercase string :- The quick brown fox

Enter 2nd lowercase string :- jumps over the lazy dog


Output = 24

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.

67) Write a Python program to remove all consecutive duplicates of a given


string.
Program :- from

itertools import
groupby

a=input("Enter a string

:- ") b=[] for

(key,range) in

groupby(a):

b.append(key) print("New

String :-

",''.join(b))
Output :-

Enter a string :- abraaacaadbaaxa


New String :- abracadbaxa

Explanation :-

The groupby module is imported from the itertools package.


A string is accepted from the user in variable ‘a’.
A for loop is iterated on the string after removing the consecutive duplicates
from it.
The key returned is then inserted into the list b.
All the elements of the list is converted into a string using the join() function.
The new string obtained is subsequently displayed.
68) Write a Python program to generate two strings from a given string. For the

first string, use the characters that occur only once, and for the second, use the

characters that occur multiple times in the said string. Program :-

a=input("Enter a string :- ") b=c='' for d in a:

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

First String :- roximtely

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

given strings. Program :- from difflib import SequenceMatcher a=input("Enter

1st string :- ") b=input("Enter

2nd string :- ") c=SequenceMatcher(None,a,b)

d=c.find_longest_match(0,len(a)

,0,len(b)) if(d.size!=0):

print("Longest common substring :-


",a[d.a:d.a+d.size]) else: print("Longest common substring

is not present")

Output :-

Enter 1st string :- xyabcdefghyy

Enter 2nd string :- pqbcdexy

Longest common substring :- bcde

Explanation :-

SequencMatcher module is imported from the package difflib.


Two strings are accepted from the user in variables ‘a’ & ‘b’.
The SequenceMatcher function is called & ‘None’, ‘a’, ‘b’ are passed onto
it.
The value returned by it is stored in a variable ‘c’.
The longest common substring (if any) is found out by using the
find_longest_match() function and the same is stored in variable ‘d’. If the
length of ‘d’ is not zero, then the longest substring is displayed using
string slicing.
Otherwise, "Longest common substring is not present" message is displayed.

70) Write a Python program that concatenates uncommon characters from two

given strings. Program :- a=input("Enter 1st string :- ") b=input("Enter 2nd

string :- ") d='' for c in a: if c not in b and c not in d: d+=c for c in b:

if c not in a and c not in d:

d+=c

print("Uncommon Characters :-",d)


Output :-

Enter 1st string :- laptop

Enter 2nd string :- lonely

Uncommon Characters :- aptney

Explanation :- Two strings are accepted from the user in

variables ‘a’ & ‘b’. A blank string named ‘d’ is also

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

string in a single traversal. Program :- a=input("Enter a

string :- ") b=[c for c in a if c!=' '] d=len(a)-len(b) e='

'*d e='"'+e+''.join(b)+'"

' print("New String


:-",e)

Output :-

Enter a string :- Python is very easy

New String :- " Pythonisveryeasy"

Explanation :-

A string is accepted from the user in variable ‘a’.


The entire string is traversed & a list ‘b’ is created without any whitespaces.
The number of spaces is calculated by subtracting the length of the newly
created list from the length of the original string & stored in a variable ‘b’.
In a new string ‘e’, a whitespace is replicated by the value of ‘b’.
The string ‘e’ is further concatenated with two double quotation marks along
with the list ‘b’ using the join() operator. The new string created is then
displayed.

72) Write a Python program to remove all characters except a specified

character from a given string. Program :- a=input("Enter a string :-

") b=input("Enter a

character :- ") c='' for d in

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

characters & numeric values in a given string. Program :- a=input("Enter a

string :- ") l=u=s=d=0 for b in a: if(b.isupper()): u+=1

elif(b.islower()): l+=1 elif(b.isdigit()):

d+=1 else:

s+=1

print("Number of Lower Case characters

=",l) print("Number of Upper


Case characters =",u) print("Number of

Special characters =",s) print("Number

of

Digits =",d) Output :-

Enter a string :- jcn78ICh,O'L>34

Number of Lower Case characters = 4


Number of Upper Case characters = 4
Number of Special characters = 3

Number of Digits = 4

Explanation :-

A string is accepted from the user in variable ‘a’.


Four variables l,u,s,d are initialized with 0. A for loop
with index variable ‘b’ is iterated on string ‘a’.
If the character in variable ‘b’ is an uppercase character, the value of ‘u’ is
increased by 1. If it is a lowercase character, the value of ‘l’ is increased by 1. If
it is a digit, the value of ‘d’ is increased by 1.
Otherwise, the value of ‘s’ is increased by 1.
After the termination of the for loop, the values of all 4 variables are displayed.

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)

i=p=q=0 for j,c in enumerate(a,1):

y-

=x[c]>0 x[c]-=1 if

not y:

while i<q and

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 :-

Enter 1st string :- PRWSOERIUSFK

Enter 2nd string :- OSU


Minimum Window :- OERIUS

Explanation :-

The collections package is imported at the beginning of the program.


Two strings are accepted from the user in variables ‘a’ & ‘b’.
The characters & the length of the second string are stored in variables ‘x’
& ‘y’ respectively.
Three variables ‘p’, ’q’ & ‘i’ are initialized with 0. A for loop with
index variables ‘j’ & ‘c’ is iterated through the first string.
Within its body, first the missing characters are decremented. Then, if all the
characters are found, the required window is optimized.
All the characters are removed from the left hand side of the string. If
the new window obtained is smaller than the initial one, the window is
updated.
The minimum window obtained is displayed using the concept of string slicing.
75) Write a Python program to find the smallest window that contains all
characters in a given string. Program :-
from collections import defaultdict
a=input("Enter a string :- ")
b=len(a) c=len(set([d for d in a]))
e,f,g,h=0,0,-

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

g=f print("Smallest Window :-

",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

string of lowercase alphabets with exactly k distinct (given) characters.

Program :- a=input("Enter a lowercase string :- ") k=int(input("Enter the value

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):

break print("Number of substrings

:-",r)

Output :-

Enter a lowercase string :- apollo


Enter the value of 'k' :- 3
Number of substrings :- 4

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

Non-Empty Substrings :- ",int(b*(b+1)/2));

Output :-

Enter a string :- python

Number of Non-Empty Substrings :- 21

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

string (lower & uppercase characters) as in the English alphabet. Program :-

a=input("Enter a string :- ") c=0 for b in range(len(a)):

if(b==ord(a[b])ord('A')) or

(b==ord(a[b])-ord('a')):
c+=1 print("Number of characters

=",c)

Output :-

Enter a string :- ijcsetgf

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 :-

Enter a string :- honesty is the best policy

Largest Word :- honesty

Smallest Word :- is

Explanation :-

A string is accepted from the user in variable ‘a’.


All the words of the string are inserted in a list using the split() function.
The first word of the list is copied is stored in 2 variables, namely ‘c’ & ‘d’.
A for loop is iterated on the list created. If the length of the word stored in
variable ‘c’ is greater than the length of the current word in ‘a’, the word in
‘c’ is replaced by the word in variable ‘a’.
If the length of the word stored in variable ‘d’ is smaller than the length of the
current word in ‘a’, the word in ‘d’ is replaced by the word in variable ‘a’. After
the termination of the for loop, the words in ‘c’ & ‘d’ are displayed.
80) Write a Python program to count the number of substrings with the same
first & last characters in a given string. Program :- a=input("Enter a string

:- ")

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 :-

Enter a string :- amazon

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

‘Not Found’. Program :- a=input("Enter a string :- ") b=input("Enter a

substring :- ") if b in a: print("Index of the substring =",a.index(b)) else:

print("Not Found")

Output :-

Enter a string :- approximately

Enter a substring :- pro

Index of the substring = 2

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

given width. Program :- import textwrap a=input("Enter a string :- ")

b=int(input("Enter the required width :- ").strip()) print("Required Output :-")

print(textwrap.fill(a,b))

Output :-

Enter a string :- Python is very easy.

Enter the required width :- 9

Required

Output :Python

is very easy.

Explanation :-

The textwrap module is imported at the beginning of the string. A


string & a width is accepted from the user.
The required paragraph is displayed using the fill() function of the textwrap
module.
83) Write a Python program to print four integer values – decimal, octal,
hexadecimal (capitalized), binary – in a single line. Program :-

a=int(input("Enter an integer :- "))


x=y=z=a o=h=b=''

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\

tOctal\tHexadeci mal\tBinary") print(a,"\

t",o,"\t",h,"\t\t",b)

Output :-

Enter an integer :- 266

DecimalOctalHexadecimalBinary

266 412 10A 100001010


Explanation :-
An integer in accepted from the user in variable ‘a’. A copy of the integer in
stored in variables ‘x’, ‘y’, & ‘z’. Three empty strings namely, ‘o’, ‘h’, &
‘b’ are created.
Using the first while loop, the octal equivalent of the given integer is
calculated and stored as a string in variable ‘o’. String concatenation &
floor division is used.
Using the second while loop, the binary equivalent of the given integer is
calculated and stored as a string in variable ‘b’. Here also string concatenation
& floor division is used.
Using the third while loop, the hexadecimal equivalent of the given integer is
calculated and stored as a string in variable ‘h’. Here along with string
concatenation & floor division, the concept of ASCII values is also used.
The given integer in decimal, binary, octal & hexadecimal equivalent form is
displayed in the same line with the help of “\t”.

84) Write a Python program to swap cases in a given string. Program :-

a=input("Enter a string :- ") b='' for c in a: if(c.isupper()): b+=c.lower()

elif(c.islower()):

b+=c.upper()

else:

b+=c

print("New

String :-",b)
Output :-

Enter a string :- NumPy

New String :- nUMpY

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.

85) Write a Python program to convert a given Bytearray to a Hexadecimal


string. Program :- a=eval(input("Enter a Bytearray :- "))
b=''.join('{:02x}'.format(p) for p in a) print("Hexadecimal String :-",b)

Output :-

Enter a Bytearray :- [111,12,45,67,109]

Hexadecimal String :- 6f0c2d436d

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.

86) Write a Python program to delete all occurrences of a specified character in


a given string.

Program :-

a=input("Enter a string :- ") b=input("Enter

a specified character

:- ") print("Modified

String :-",a.replace(b,""))

Output :-

Enter a string :- india is great

Enter a specified character :- i

Modified String :- nda s great

Explanation :- A string as well as a specified character is accepted from

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

strings. Program :- a=input("Enter 1st string :- ") b=input("Enter 2nd

string :- ") s='' for c in

a: if c in b and not c

in s:

s+=c print("The intersection

is :-",s)

Output :-

Enter 1st string :- Python3

Enter 2nd string :- python2.7

The intersection is :- ython

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

letter, a lower case letter, a number & a minimum length. Program :-

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")

Output :- Enter a 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.

89) Write a Python program to remove unwanted characters from a given

string. Program :- a=input("Enter a string :- ") b='' for c in a: if c.isalnum()

or c=='

': b+=c
print("New String

:-",b)

Output :-

Enter a string :- A%^!B#*CD

New String :- ABCD

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.

Program :- a=input("Enter a string :- ") b=a.split() c=[] for a in b: if a not in

c:

c.append(a) print("New

String :-

",' '.join(c))

Output :-

Enter a string :- Python Exercises Practice Solution Exercises

New String :- Python Exercises Practice Solution


Explanation :-
A string is accepted from the user. A list ‘b’ is created containing all the words
of the input string using the split() function. An empty list ‘c’ is also
created. A for loop is iterated on the input string. If the word is not
present the list ‘c’, the word is inserted in the list.
All the words of the list ‘c’ are converted to a string with a whitespace between
them using the join() function. The new string obtained is then displayed.
91) Write a Python program to convert a given heterogeneous list of scalars

into a string. Program :- a=eval(input("Enter a list :- ")) for b in range(len(a)):

a[b]=str(a[b]) print("Output

String :-

",','.join(a))

Output :-

Enter a list :- ['Red',100,-50,'green','w,3,r',12.12,False]

Output String :- Red,100,-50,green,w,3,r,12.12,False

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

strings. Program :- import difflib s1=input("Enter 1st string :- ")

s2=input("Enter 2nd string :- ") c=difflib.SequenceMatcher(a=s1.lower(

),b=s2.lower()) print("String Similarity

=",c.ratio())
Output :-

Enter 1st string :- character

Enter 2nd string :- at


String Similarity = 0.36363636363636365

Explanation :-

The difflib module is imported at the beginning of the program.


Two strings are accepted from the user in variables ‘s1’ & ‘s2’.
A SequenceMatcher object is created with the lowercase versions of the input
strings. The similarity ratio between the two strings is computed &
subsequently displayed.

93) Write a Python program to extract numbers from a given string. Program

:- a=input("Enter a string :- ") b=[int(c) for c in a.split() if c.isdigit()]

print("Numbers extracted =",b) Output :-

Enter a string :- Red 12 Green 55

Numbers extracted = [12, 55]


Explanation :- A string is accepted from the user in
variable ‘a’.
If the integers of the input string are digits, then list comprehension method is
used to create a list which contains all the integers.
The list created contains all the numbers of the string & is subsequently
displayed.
94) Write a Python program to convert a hexadecimal color code to a tuple of

integers corresponding to its RGB components. Program :- a=input("Enter a

hexadecimal color code :- ") b=tuple(int(a[c:c+2],16) for c in (0,2,4))

print("Tuple of integers

=",b)

Output :-

Enter a hexadecimal color code :- FFA501

Tuple of integers = (255, 165, 1)


Explanation :-

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 :-

Enter a tuple containing RGB values :- (255,165,1)

Hexadecimal color code = FFA501

Explanation :- A tuple containing RGB values is accepted from the user


using eval.
To convert RGB values to a hexadecimal color code, string formatting is used.
The result obtained is stored in variable ‘b’ & the same is displayed.
96) Write a Python program to convert a given string to Camelcase.

Program :- from re import sub a=input("Enter a string :- ") a=sub(r"(_|-)

+","

",a).title().replace(" ","")

b=''.join([a[0].lower(),a[1:]])

print("Camelcase :-",b)

Output :-

Enter a string :- Java Script


Camelcase :- javaScript

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.

Program :- from re import sub a=input("Enter a string :- ") b='_'.join(sub('([A-

Z][a-z]+)',r'\1',sub('([A-

Z]+)',r'\1',a.replace('-',' '))).split()).lower() print("Snake case :-

",b)

Output :-

Enter a string :- Java Script

Snake case :- java_script

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.

Program :- a=input("Enter a string :- ") print("New String :",a[0].lower()+a[1::])

Output :-

Enter a string :- Python

New String :- python

Explanation :- A string is accepted from

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.

Program :- a="This\nis a\nmultiline\nstring.\n" print("Original String :-")

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

contains duplicate characters or not. Return True or False. Program :-

a=input("Enter a sentence :- ") b=a.lower().split() f=0 for a in b:

c=0 for d in

range(97,123): if

chr(d) in a:

c=a.count(chr(d)

) if c>1: f=1 if f==1:

break if f==0: print("True") print("String do

not contain words with duplicate characters!!!")

else: print("False") print("String contain

words with duplicate characters!!!")

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.

Program :- a=input("Enter 1st string :- ") b=input("Enter 2nd string :- ") if

a.isdigit() and

b.isdigit():
c=int(a)+int(b)

print("Sum of",a,"&",b,"is

=",c) else: print("Error

in input!") Output :-

Enter 1st string :- 34

Enter 2nd string

:- 23 Sum of 34

& 23 is = 57

Explanation :- Two strings are accepted

from the user.

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.

102) Write a Python program to remove punctuation from a given string.

Program :- a=input("Enter a string :- ")

p=[",","?",".","!",";",":","","_","'",'"',"(",")","{","}","[","]"] for b in p:

s=a.replace(b,"
") a=s

print("New

String :-",s)
Output :-

Enter a string :- String! With. Punctuation?

New String :- String With Punctuation

Explanation :- A string is accepted from the user in


variable ‘a’.
A list ‘p’ is created which contains all the punctuation marks. A for loop is
iterated through every punctuation of the created list. If a punctuation is present
in the input string, then it is removed using the replace() function and stored in
a new string ‘s’. The string in ‘s’ is copied onto the string ‘a’.
After the termination of the for loop, the new string ‘s’ obtained is displayed.

103) Write a Python program to replace each character of a word of length five

and more with a hash character (#). Program :- a=input("Enter a string :-

")

b=a.split() for a in range(len(b)): if

len(b[a])>=5:
b[a]="#"*len(b[ a])

a=" ".join(b)

print("New

String :-",a)
Output :-

Enter a string :- Honesty is the best policy

New String :- ####### is the best ######

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

New String :- Dow Jones Industrial Average

Explanation :- A string is accepted from the user at the beginning of the

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 :- ")

b=a.partition('@') c='' for

a in b[0]: if a.isalpha():

c+=a print("Name is

:-",c)

Output :-

Enter an email address :- fully-qualified-domain@example.com

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.

106) Write a Python program to remove repeated consecutive characters &


replace them with single letters & print a updated string. Program :-

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 :-

Enter a string :- aabbbcdeffff


New String :- abcdef

Explanation :- A string is accepted from the user and stored in a variable


named ‘a’. A new string ‘b’ containing only the first character of the
input string is created.
A for loop with index variable ‘c’ is iterated through every character of the
input string.
If the last character of the string ‘b’ is the character of the cth index of the string
‘a’, then continue statement is executed otherwise the character is concatenated
with the string ‘b’. The new string obtained in ‘b’ is the required string & is
subsequently displayed.

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

times =",c) Output :-

Enter 1st string :- Red White


Enter 2nd string :- Red White

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 :-

Enter a string :- White

New String :- #W##h#i#t#e


Explanation :-
A string is accepted from the user in variable ‘a’. A string ‘b’ is created
containing all the vowels in both uppercase & lowercase. An empty string
‘s’
is also created.
A for loop is iterated through every character of the input string. If the character
is not in string ‘b’, then a hash followed by the character itself followed by
another hash is concatenated with the string ‘s’. After that continue statement is
executed.

The character is concatenated with string ‘s’ if it’s a vowel.


After the termination of the loop, the new string obtained is displayed.

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 :-

a=input("Enter a range of years :- ") b=a.partition("-

")

c=0 for a in

range(int(b[0]),int(b[2])+

1): if int(a)%4==0:

c+=1

print("Number of Leap Years


=",c)

Output :-

Enter a range of years :- 2000-2024

Number of Leap Years = 7

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 given word. Program :- a=input("Enter a word :- ") c='' for b

in a: if

b.isupper(): c+=' '+b

else: c+=b

print("Output :-

",c)

Output :-
Enter a word :- PythonExercisesPracticeSolution

Output :- Python Exercises Practice Solution

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

their respective numbers. Program :- a=input("Enter a string :- ") b=a.lower()

print("Required Output :-") for a in b: if a.isalpha(): print(ord(a)-

96,end=" ")

Output :-

Enter a string :- Python Tutorial

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

strings. Return the result in the same string representation. Program :-

a=input("Enter 1st number string :- ") b=input("Enter 2nd number string :- ")

c='"'+str(int(a)+int(b))+'"' print("Sum

=",c)

Output :-

Enter 1st number string :- 1000


Enter 2nd number string :- 10

Sum = "1010"

Explanation :- Two number strings are accepted from

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

first character of a given string of words. Program :- a=input("Enter a

string/sentence :-

") b=a.split()

b.sort() print("New Sorted

String is :-") print("

".join(b))

Output :-

Enter a string/sentence :- Red Green Black White Pink

New Sorted String is :-

Black Green Pink Red White


Explanation :- A string/sentence is accepted from the user in a

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.

You might also like