CH-9 STRING MANIPULATION TYPE-C
Question 1
Write a program to count the number of times a character
occurs in the given string.
Solution
str = input("Enter the string: ")
ch = input("Enter the character to count: ");
c = str.count(ch)
print(ch, "occurs", c, "times")
Output
Enter the string: KnowledgeBoat
Enter the character to count: e
e occurs 2 times
Question 2
Write a program which replaces all vowels in the string with
'*'.
Solution
str = input("Enter the string: ")
newStr = ""
for ch in str :
lch = ch.lower()
if lch == 'a' ¥
or lch == 'e' ¥
or lch == 'i' ¥
or lch == 'o' ¥
or lch == 'u' :
newStr += '*'
else :
newStr += ch
print(newStr)
Output
Enter the string: Computer Studies
C*mp*t*r St*d**s
Question 3
Write a program which reverses a string and stores the
reversed string in a new string.
Solution
str = input("Enter the string: ")
newStr = ""
for ch in str :
newStr = ch + newStr
print(newStr)
Output
Enter the string: computer studies
seiduts retupmoc
Question 4
Write a program that prompts for a phone number of 10
digits and two dashes, with dashes after the area code and
the next three numbers. For example, 017-555-1212 is a legal
input. Display if the phone number entered is valid format
or not and display if the phone number is valid or not (i.e.,
contains just the digits and dash at specific places.)
Solution
phNo = input("Enter the phone number: ")
length = len(phNo)
if length == 12 ¥
and phNo[3] == "-" ¥
and phNo[7] == "-" ¥
and phNo[:3].isdigit() ¥
and phNo[4:7].isdigit() ¥
and phNo[8:].isdigit() :
print("Valid Phone Number")
else :
print("Invalid Phone Number")
Output
Enter the phone number: 017-555-1212
Valid Phone Number
=====================================
Enter the phone number: 017-5A5-1212
Invalid Phone Number
Question 5
Write a program that should do the following :
• prompt the user for a string
• extract all the digits from the string
• If there are digits:
o sum the collected digits together
o print out the original string, the digits, the sum of
the digits
• If there are no digits:
o print the original string and a message "has no
digits"
Sample
• given the input : abc123
prints abc123 has the digits 123 which sum to 6
• given the input : abcd
prints abcd has no digits
Solution
str = input("Enter the string: ")
sum = 0
digitStr = ''
for ch in str :
if ch.isdigit() :
digitStr += ch
sum += int(ch)
if not digitStr :
print(str, "has no digits")
else :
print(str, "has the digits", digitStr, "which sum to", sum)
Output
Enter the string: abc123
abc123 has the digits 123 which sum to 6
=====================================
Enter the string: KnowledgeBoat
KnowledgeBoat has no digits
Question 6
Write a program that should prompt the user to type some
sentence(s) followed by "enter". It should then print the
original sentence(s) and the following statistics relating to
the sentence(s) :
• Number of words
• Number of characters (including white-space and
punctuation)
• Percentage of characters that are alphanumeric
Hints
• Assume any consecutive sequence of non-blank
characters is a word.
Solution
str = input("Enter a few sentences: ")
length = len(str)
spaceCount = 0
alnumCount = 0
for ch in str :
if ch.isspace() :
spaceCount += 1
elif ch.isalnum() :
alnumCount += 1
alnumPercent = alnumCount / length * 100
print("Original Sentences:")
print(str)
print("Number of words =", (spaceCount + 1))
print("Number of characters =", (length + 1))
print("Alphanumeric Percentage =", alnumPercent)
Output
Enter a few sentences: Python was conceived in the late 1980s by
Guido van Rossum at Centrum Wiskunde & Informatica (CWI) in the
Netherlands. Its implementation began in December 1989. Python 3.0
was released on 3 December 2008.
Original Sentences:
Python was conceived in the late 1980s by Guido van Rossum at
Centrum Wiskunde & Informatica (CWI) in the Netherlands. Its
implementation began in December 1989. Python 3.0 was released on
3 December 2008.
Number of words = 34
Number of characters = 206
Alphanumeric Percentage = 80.48780487804879
Question 7
Write a Python program as per specifications given below:
• Repeatedly prompt for a sentence (string) or for 'q' to
quit.
• Upon input of a sentence s, print the string produced
from s by converting each lower case letter to upper
case and each upper case letter to lower case.
• All other characters are left unchanged.
For example,
Please enter a sentence, or 'q' to quit : This is the Bomb!
tHIS IS THE bOMB!
Please enter a sentence, or 'q ' to quit : What's up Doc ???
wHAT'S UP dOC ???
Please enter a sentence, or 'q' to quit : q
Solution
while True :
str = input("Please enter a sentence, or 'q' to quit : ")
newStr = ""
if str.lower() == "q" :
break
for ch in str :
if ch.islower() :
newStr += ch.upper()
elif ch.isupper() :
newStr += ch.lower()
else :
newStr += ch
print(newStr)
Output
Please enter a sentence, or 'q' to quit : This is the Bomb!
tHIS IS THE bOMB!
Please enter a sentence, or 'q' to quit : What's up Doc ???
wHAT'S UP dOC ???
Please enter a sentence, or 'q' to quit : q
Question 8
Write a program that does the following :
• takes two inputs : the first, an integer and the second,
a string
• from the input string extract all the digits, in the order
they occurred, from the string.
o if no digits occur, set the extracted digits to 0
• add the integer input and the digits extracted from the
string together as integers
• print a string of the form :
"integer_input + string_digits = sum"
For example :
For inputs 12, 'abc123' → '12 + 123 = 135'
For inputs 20, 'a5b6c7' → '20 + 567 =587'
For inputs 100, 'hi mom' → '100 + 0 = 100'
Solution
num = int(input("Enter an integer: "))
str = input("Enter the string: ")
digitsStr = ''
digitsNum = 0;
for ch in str :
if ch.isdigit() :
digitsStr += ch
if digitsStr :
digitsNum = int(digitsStr)
print(num, "+", digitsNum, "=", (num + digitsNum))
Output
Enter an integer: 12
Enter the string: abc123
12 + 123 = 135
=====================================
Enter an integer: 20
Enter the string: a5b6c7
20 + 567 = 587
=====================================
Enter an integer: 100
Enter the string: hi mom
100 + 0 = 100
Question 9
Write a program that takes two strings from the user and
displays the smaller string in single line and the larger
string as per this format :
1st letter last letter
2nd letter 2nd last letter
3rd letter 3rd last letter
For example,
if the two strings entered are Python and PANDA then the
output of the program should be :
PANDA
P n
y o
t h
Solution
str1 = input("Enter first string: ")
str2 = input("Enter second string: ")
small = str1
large = str2
if len(str1) > len(str2) :
large = str1
small = str2
print(small)
lenLarge = len(large)
for i in range(lenLarge // 2) :
print(' ' * i, large[i], ' ' * (lenLarge - 2 * i),
large[lenLarge - i - 1], sep='')
Output
Enter first string: Python
Enter second string: PANDA
PANDA
P n
y o
t h
10
Question 10
Write a program to convert a given number into equivalent
Roman number (store its value as a string). You can use
following guidelines to develop solution for it:
• From the given number, pick successive digits,
using %10 and /10 to gather the digits from right to
left.
• The rules for Roman Numerals involve using four pairs
of symbols for ones and five, tens and fifties, hundreds
and five hundreds. An additional symbol for thousands
covers all the relevant bases.
• When a number is followed by the same or smaller
number, it means addition. "II" is two 1's = 2. "VI" is 5 +
1 = 6.
• When one number is followed by a larger number, it
means subtraction. "IX" is 1 before 10 = 9. "IIX isn't
allowed, this would be "VIII". For numbers from 1 to 9,
the symbols are "I" and "V", and the coding works like
this. "I" , "II", "III", "IV", "V", "VI", "VII", "VIII", "IX".
• The same rules work for numbers from 10 to 90, using
"X" and "L". For numbers from 100 to 900, using the
symbols "C" and "D". For numbers between 1000 and
4000, using "M".
Here are some examples. 1994 = MCMXCIV, 1956 = MCMLVI,
3888= MMMDCCCLXXXVIII
Solution
n = int(input("Enter the number: "))
num = (1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4,
1)
rom = ('M', 'CM', 'D', 'CD','C',
'XC','L','XL','X','IX','V','IV','I')
result = ''
for i in range(len(num)) :
count = int(n / num[i])
result += str(rom[i] * count)
n -= num[i] * count
print(result)
Output
Enter the number: 1994
MCMXCIV
=====================================
Enter the number: 1956
MCMLVI
=====================================
Enter the number: 3888
MMMDCCCLXXXVIII
11
Question 11
Write a program that asks the user for a string (only single
space between words) and returns an estimate of how
many words are in the string. (Hint. Count number of
spaces)
Solution
str = input("Enter a string: ")
count = 0
for ch in str :
if ch.isspace() :
count += 1
print("No of words =", (count + 1))
Output
Enter a string: Python was conceived in the late 1980s by Guido
van Rossum at Centrum Wiskunde & Informatica (CWI) in the
Netherlands.
No of words = 20
12
Question 12
Write a program to input a formula with some brackets and
checks, and prints out if the formula has the same number
of opening and closing parentheses.
Solution
str = input("Enter a formula: ")
count = 0
for ch in str :
if ch == '(' :
count += 1
elif ch == ')' :
count -= 1
if count == 0 :
print("Formula has same number of opening and closing
parentheses")
else :
print("Formula has unequal number of opening and closing
parentheses")
Output
Enter a formula: s(s-a)(s-b)(s-c)
Formula has same number of opening and closing parentheses
=====================================
Enter a formula: s((s-a)(s-b)(s-c)
Formula has unequal number of opening and closing parentheses
13
Question 13
Write a program that inputs a line of text and prints out the
count of vowels in it.
Solution
str = input("Enter a string: ")
count = 0
for ch in str :
lch = ch.lower()
if lch == 'a' ¥
or lch == 'e' ¥
or lch == 'i' ¥
or lch == 'o' ¥
or lch == 'u' :
count += 1
print("Vowel Count =", count)
Output
Enter a string: Internet of Things
Vowel Count = 5
14
Question 14
Write a program to input a line of text and print the biggest
word (length wise) from it.
Solution
str = input("Enter a string: ")
words = str.split()
longWord = ''
for w in words :
if len(w) > len(longWord) :
longWord = w
print("Longest Word =", longWord)
Output
Enter a string: TATA FOOTBALL ACADEMY WILL PLAY AGAINST MOHAN
BAGAN
Longest Word = FOOTBALL
15
Question 15
Write a program to input a line of text and create a new line
of text where each word of input line is reversed.
Solution
str = input("Enter a string: ")
words = str.split()
newStr = ""
for w in words :
rw = ""
for ch in w :
rw = ch + rw
newStr += rw + " "
print(newStr)
Output
Enter a string: Python is Fun
nohtyP si nuF