0% found this document useful (0 votes)
412 views9 pages

CS CH 10 - String Manipulation

This document contains 15 questions related to string manipulation in Python. The questions cover topics like counting characters in a string, replacing characters, reversing strings, validating phone numbers, extracting digits from strings, and analyzing strings. For each question, one or more solutions are provided and sample input/output is given to demonstrate the solutions working as expected.

Uploaded by

Rahul Rana
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
412 views9 pages

CS CH 10 - String Manipulation

This document contains 15 questions related to string manipulation in Python. The questions cover topics like counting characters in a string, replacing characters, reversing strings, validating phone numbers, extracting digits from strings, and analyzing strings. For each question, one or more solutions are provided and sample input/output is given to demonstrate the solutions working as expected.

Uploaded by

Rahul Rana
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

COMPUTER SCIENCE

CHAPTER 10 - STRING MANIPULATION


Type C : Programming Practice/Knowledge based Questions

Q 1. Write a program to count the number of times a character occurs in


the given string.
SOLUTION
str = input("Enter a String : ")
chr = input("Enter a Character : ")
m = 0
for i in str :
if i == chr :
m += 1
print(chr, "occurs", m, "times in", str)
OR
str = input("Enter a string : ")
chr = input("Enter a character : ");
m = str.count(chr)
print(chr, "occurs", m, "times in", str)
OUTPUT
Enter a String : computer science
Enter a Character : e
e occurs 3 times in computer science

Q 2. Write a program which replaces all vowels in the string with '*'.
SOLUTION
str = input("Enter a String : ")
vowel = ["a", "e", "i", "o", "u", "A", "E", "I", "O", "U"]
new = "" # Empty string
for i in str :
if i in vowel :
new += "*"
else :
new += i
print("New String :", new)
OUTPUT
Enter a String : Programming
New String : Pr*gr*mm*ng

Q 3. Write a program which reverses a string and stores the reversed


string in a new string.
SOLUTION
str = input("Enter the string: ")
new = ""
for ch in str :
new = ch + new
print("Reversed String : ", new)
OR
str = input('Enter a String : ')
ln = len(str)
new = ""
for i in range(-1, (-ln-1), -1) :
new += str[i]
print("Reversed String : ", new)
OUTPUT
Enter a String : python
Reversed String : nohtyp

Q 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
num = input("Enter Phone Number : ")
valid = len(num) == 12 and num[3] == "-" and
num[4:7].isdigit() and num [7] == "-" and num[8:13].isdigit()
and num[:3].isdigit()
if valid:
print("It is valid number")
else:
print("It is not valid number")
OR
num = input("Enter Phone Number : ")
if len(num) == 12:
if num[3] == "-" :
if num[4:7].isdigit():
if num [7] == "-":
if num[8: 13].isdigit():
if num[:3].isdigit():
print("It is valid number")
else:
print("It is not valid number")
else:
print("It is not valid number")
else:
print("It is not valid number")
else:
print("It is not valid number")
else:
print("It is not valid number")
else:
print("It is not valid number")
OUTPUT
Enter Phone Number : 122-233-4545
It is valid number

Q 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:
▲ sum the collected digits together
▲ print out the original string, the digits, the sum of the digits
▲ If there are no digits:
▲ 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 a String : ")
digit = ""
sum = 0
for ch in str :
if ch.isdigit() :
digit += ch
sum += int(ch)
if digit != "" :
print(str, "has the digits", digit, " which sum to", sum)
else :
print(str, "has no digits")
OUTPUT
Enter a String : xyz789
xyz789 has the digits 789 which sum to 24

Q 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

sen = input("Enter a few sentences: ")


length = len(sen)
spaceCount = 0
alnumCount = 0
for ch in sen :
if ch.isspace() :
spaceCount += 1
elif ch.isalnum() :
alnumCount += 1
alnumPercent = (alnumCount / length) * 100
print("Number of words :", (spaceCount + 1))
print("Number of characters :", length)
print("Alphanumeric Percentage :", alnumPercent, "%")
OUTPUT
Enter a few sentences : people die if they are killed...
Number of words : 6
Number of characters : 32
Alphanumeric Percentage : 75.0 %

Q 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(enter 'q' to quit) :
")
newStr = ""
if str.lower() == "q" :
break
else:
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(enter 'q' to quit) : You wanna say
something?
yOU WANNA SAY SOMETHING?
Please enter a sentence(enter 'q' to quit) : No, I Don't
wanna
nO,i dON'T WANNA
Please enter a sentence(enter 'q' to quit) : q

Q 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.
▲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 a string : ")
digit = ''
if digit.isalpha() :
digit = 0
for ch in str :
if ch.isdigit() :
digit += ch
print(num, "+", digit, "=", (num + int(digit)))
OUTPUT
Enter an integer : 9
Enter a string : xyz789
9 + 789 = 798

Q 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 Word :", (count+1))
OUTPUT
Enter a String : just because you're correct doesn't mean
you're right
No. of Word : 8

Q 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 : (n/2)(2a + (n - 1)d)
Formula has same number of opening and closing parentheses.

Q 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 : ")
vowel = ["a", "e", "i", "o", "u", "A", "E", "I", "O", "U"]
count = 0
for ch in str :
if ch in vowel :
count += 1
print("No. of vowels :", count)
OUTPUT
Enter a String : just because you’re correct doesn’t mean
you’re right
No. of vowels : 18

Q 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()
longest = ''
for w in words :
if len(w) > len(longest) :
longest = w
print("Longest Word :", longest)
OUTPUT
Enter a string: I ran out of Ideas
Longest Word : Ideas

Q 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 : really nothing
yllaer gnihton

— By Nitin Bhatt

You might also like