String Manipulation C.W Notes
String Manipulation C.W Notes
Question 1
Write a Python script that traverses through an input string and prints its characters in
different lines — two characters per line.
Answer
Output
Question 2
Out of the following operators, which ones can be used with strings in Python?
Answer
Question 3
Answer
FuntrialOotyOotyOoty
Question 4
Answer
'abc' + .3 is not a legal string operation in Python. The operands of + operator should be both
string or both numeric. Here one operand is string and other is numeric. This is not allowed in
Python.
Question 5
Can you say strings are character lists? Why? Why not?
Answer
Strings are sequence of characters where each character has a unique index. This implies that
strings are iterable like lists but unlike lists they are immutable so they cannot be modified at
runtime. Therefore, strings can't be considered as character lists. For example,
str = 'cat'
# The below statement
# is INVALID as strings
# are immutable
str[0] = 'b'
Question 6
Given a string S = "CARPE DIEM". If n is length/2 (length is the length of the given string),
then what would following return?
(a) S[: n]
(b) S[n :]
(c) S[n : n]
(d) S[1 : n]
(e) S[n : length - 1]
Answer
(a) CARPE
(b) DIEM
(c) (Empty String)
(d) ARPE
(e) DIE
Question 7
From the string S = "CARPE DIEM", which ranges return "DIE" and "CAR"?
Answer
Question 8
What happens when from a string slice you skip the start and/or end values of the slice?
Answer
If start value is skipped, it is assumed as 0 i.e. the slice begins from the start of the string.
If end value is skipped, it is assumed as the last index of the string i.e. the slice extends till
the end of the string.
Question 9
Answer
1. hello world
2. HELLO WORLD
3. -1
4. 6
5. -1
6. False
7. False
8. True
9. False
Explanation
1. upper() first converts all letters of "Hello World" to uppercase. Then "HELLO
WORLD".lower() converts all letters to lowercase.
2. lower() first converts all letters of "Hello World" to lowercase. Then "hello
world".upper() converts all letters to uppercase.
3. "Hello World".find("Wor", 1, 6) searches for the presence of substring "Wor"
between 1 and 6 indexes of string "Hello World". Substring from 1 to 6 index is "ello
W". As "Wor" is not present in this hence the result is False.
4. "Hello World".find("Wor") searches for the presence of substring "Wor" in the entire
"Hello World" string. Substring "Wor" starts at index 6 of "Hello World" hence the
result is 6.
5. "Hello World".find("wor") searches for the presence of substring "wor" in the entire
"Hello World" string. find() performs case sensitive search so "wor" and "Wor" are
different hence the result is -1.
6. "Hello World".isalpha( ) checks if all characters in the string as alphabets. As a space
is also present in the string hence it returns False.
7. "Hello World".isalnum( ) checks if all characters in the string are either alphabets or
digits. As a space is also present in the string which is neither an alphabet nor a string
hence it returns False.
8. "1234".isdigit( ) checks if all characters in the string are digits or not. As all
characters are digits hence the result is True.
9. As "FGH" in the string "123FGH" are not digits hence the result is False.
Question 10
Which functions would you choose to use to remove leading and trailing white spaces from a
given string?
Answer
lstrip() removes leading white-spaces, rstrip() removes trailing white-spaces and strip()
removes leading and trailing white-spaces from a given string.
Question 11
Try to find out if for any case, the string functions isalnum( ) and isalpha( ) return the same
result
Answer
isalnum( ) and isalpha( ) return the same result in the following cases:
1. If string contains only alphabets then both isalnum( ) and isalpha( ) return True. For
example, "Hello".isalpha() and "Hello".isalnum() return True.
2. If string contains only special characters and/or white-spaces then both isalnum( ) and
isalpha( ) return False. For example, "*#".isalpha() and "*#".isalnum() return False.
Question 12
Answer
1. isdigit()
2. find()
3. capitalize()
4. upper()
5. isupper()
6. rstrip(characters)
7. lstrip()
Question 13
In a string slice, the start and end values can be beyond limits. Why?
Answer
String slicing always returns a subsequence and empty subsequence is a valid sequence.
Thus, when a string is sliced outside the bounds, it still can return empty subsequence and
hence Python gives no errors and returns empty subsequence.
Question 14
Can you specify an out of bound index when accessing a single character from a string?
Why?
Answer
We cannot specify an out of bound index when accessing a single character from a string, it
will cause an error. When we use an index, we are accessing a constituent character of the
string. If the index is out of bounds there is no character to return from the given index hence
Python throws string index out of range error.
Question 15
Can you add two strings? What effect does ' + ' have on strings?
Answer
Yes two strings can be added using the '+' operator. '+' operator concatenates two strings.
Question 1a
print("""
1
2
3
""")
Answer
1
2
3
Question 1b
Answer
Test.
Next line.
Question 1c
Question 1d
s = '0123456789'
print(s[3], ", ", s[0 : 3], " - ", s[2 : 5])
print(s[:3], " - ", s[3:], ", ", s[3:100])
print(s[20:], s[2:1], s[1:1])
Answer
3 , 012 - 234
012 - 3456789 , 3456789
Question 1e
s ='987654321'
print (s[-1], s[-3])
print (s[-3:], s[:-3])
print (s[-100:-3], s[-100:3])
Answer
1 3
321 987654
987654 987
Question 2a
y = str(123)
x = "hello" * 3
print (x, y)
x = "hello" + "world"
y = len(x)
print (y, x)
Answer
Output
hellohellohello 123
10 helloworld
Explanation
str(123) converts the number 123 to string and stores in y so y becomes "123". "hello" * 3
repeats "hello" 3 times and stores it in x so x becomes "hellohellohello".
Question 2b
x = "hello" + \
"to Python" + \
"world"
for char in x :
y = char
print (y, ' : ', end = ' ')
Answer
Output
h : e : l : l : o : t : o : : P : y : t : h
: o : n : w : o : r : l : d :
Explanation
Inside the for loop, we are traversing the string "helloto Pythonworld" character by character
and printing each character followed by a colon (:).
Question 2c
x = "hello world"
print (x[:2], x[:-2], x[-2:])
print (x[6], x[2:4])
print (x[2:-3], x[-4:-2])
Answer
Output
he hello wor ld
w ll
llo wo or
Explanation
x[:2] ⇒ he
x[:-2] ⇒ hello wor
x[-2:] ⇒ ld
x[6] ⇒ w
x[2:4] ⇒ ll
x[2:-3] ⇒ llo wo
x[-4:-2] ⇒ or
Question 3
Carefully go through the code given below and answer the questions based on it :
1. This is a test
2. This is a
3. is a test
4. is a
5. None of these
Answer
1. This is a test
2. s is a t
3. is a test
4. is a
5. None of these
Answer
Option 2 — s is a t
Explanation
As input is 3 and inside the while loop, inputlnt decreases by 1 in each iteration so the while
loop executes 4 times for inputlnt values 3, 2, 1, 0.
1st Iteration
testStr = "This is a test"
2nd Iteration
testStr = "his is a tes"
3rd Iteration
testStr = "is is a te"
4th Iteration
testStr = "s is a t"
1. 0
2. 1
3. 2
4. 3
5. None of these
Answer
Explanation
Value of inputlnt will be -1 as till inputlnt >= 0 the while loop will continue executing.
1. False
2. True
3. 0
4. 1
5. None of these
Answer
Option 2 — True
Explanation
As input is 2 and inside the while loop, inputlnt decreases by 1 in each iteration so the while
loop executes 3 times for inputlnt values 2, 1, 0.
1st Iteration
testStr = "This is a test"
2nd Iteration
testStr = "his is a tes"
3rd Iteration
testStr = "is is a te"
After the while loop finishes executing, value of testStr is "is is a te". 't' in testStr returns True
as letter t is present in testStr.
Question 4
Carefully go through the code given below and answer the questions based on it :
testStr = "abcdefghi"
inputStr = input ("Enter integer:")
inputlnt = int(inputStr)
count = 2
newStr = ''
while count <= inputlnt :
newStr = newStr + testStr[0 : count]
testStr = testStr[2:] #Line 1
count = count + 1
print (newStr) # Line 2
print (testStr) # Line 3
print (count) # Line 4
print (inputlnt) # Line 5
(i) Given the input integer 4, what output is produced by Line 2?
1. abcdefg
2. aabbccddeeffgg
3. abcdeefgh
4. ghi
5. None of these
Answer
Option 3 — abcdeefgh
Explanation
Input integer is 4 so while loop will execute 3 times for values of count as 2, 3, 4.
1st Iteration
newStr = newStr + testStr[0:2]
⇒ newStr = '' + ab
⇒ newStr = ab
testStr = testStr[2:]
⇒ testStr = cdefghi
2nd Iteration
newStr = newStr + testStr[0:3]
⇒ newStr = ab + cde
⇒ newStr = abcde
testStr = testStr[2:]
⇒ testStr = efghi
3rd Iteration
newStr = newStr + testStr[0:4]
⇒ newStr = abcde + efgh
⇒ newStr = abcdeefgh
testStr = testStr[2:]
⇒ testStr = ghi
1. abcdefg
2. aabbccddeeffgg
3. abcdeefgh
4. ghi
5. None of these
Answer
Option 4 — ghi
Explanation
Input integer is 4 so while loop will execute 3 times for values of count as 2, 3, 4.
1st Iteration
testStr = testStr[2:]
⇒ testStr = cdefghi
2nd Iteration
testStr = testStr[2:]
⇒ testStr = efghi
3rd Iteration
testStr = testStr[2:]
⇒ testStr = ghi
1. 0
2. 1
3. 2
4. 3
5. None of these
Answer
Explanation
Looking at the condition of while loop — while count <= inputlnt, the while loop will stop
executing when count becomes greater than inputlnt. Value of inputlnt is 3 so when loop
stops executing count will be 4.
(iv) Given the input integer 3, what output is produced by Line 5?
1. 0
2. 1
3. 2
4. 3
5. None of these
Answer
Option 4 — 3
Explanation
The input is converted from string to integer and after that its value is unchanged in the code
so line 5 prints the input integer 3.
1. testStr = testStr[2:0]
2. testStr = testStr[2:-1]
3. testStr = testStr[2:-2]
4. testStr = testStr - 2
5. None of these
Answer
Option 5 — None of these
Question 5
Carefully go through the code given below and answer the questions based on it :
1. 0
2. 1
3. 2
4. 3
5. 4
Answer
Option 1 — 0
Explanation
In the input abcd, all the letters are between a and m so the condition — if ele >= 'a' and
ele <= 'm' is always true. Hence, biglnt is 0.
(ii) Given the input Hi Mom what output is produced by Line 3?
1. 0
2. 1
3. 2
4. 3
5. None of these
Answer
Option 3 — 2
Explanation
In the input Hi Mom, only two letters i and m satisfy the condition — if ele >= 'a' and
ele <= 'm'. Hence, value of littlelnt is 2.
(iii) Given the input Hi Mom what output is produced by Line 4?
1. 0
2. 1
3. 2
4. 3
5. None of these
Answer
Option 4 — 3
Explanation
In the input Hi Mom, 3 characters H, M and space are not between a and z. So for these 3
characters the statement in else part — otherlnt = otherlnt + 1 is executed. Hence, value
of otherlnt is 3.
(iv) Given the input 1+2 =3 what output is produced by Line 5?
1. 0
2. 1
3. True
4. False
5. None of these
Answer
Option 4 — False
Explanation
As all characters in the input string 1+2 =3 are not digits hence isdigit() returns False.
(v) Give the input Hi Mom, what changes result from modifying Line 1 from
1. No change
2. otherlnt would be larger
3. littlelnt would be larger
4. biglnt would be larger
5. None of these
Answer
Explanation
For letter m, now else case will be executed increasing the value of otherlnt.
Question 6
Carefully go through the code given below and answer the questions based on it :
if len(in1Str)>len(in2Str):
small = in2Str
large = in1Str
else:
small = in1Str
large = in2Str
newStr = ''
for element in small:
result = int(element) + int(large[0])
newStr = newStr + str(result)
large = large[1:]
print (len(newStr)) # Line 1
print (newStr) # Line 2
print (large) # Line 3
print (small) # Line 4
(i) Given a first input of 12345 and a second input of 246, what result is produced by Line 1?
1. 1
2. 3
3. 5
4. 0
5. None of these
Answer
Option 2 — 3
Explanation
As length of smaller input is 3, for loop executes 3 times so 3 characters are added to newStr.
Hence, length of newStr is 3.
(ii) Given a first input of 12345 and a second input of 246, what result is produced by Line 2?
1. 369
2. 246
3. 234
4. 345
5. None of these
Answer
Option 1 — 369
Explanation
1st Iteration
result = 2 + 1
⇒ result = 3
large = 2345
2nd Iteration
result = 4 + 2
⇒ result = 6
large = 345
3rd Iteration
result = 6 + 3
⇒ result = 9
large = 45
(iii) Given a first input of 123 and a second input of 4567, what result is produced by Line 3?
1. 3
2. 7
3. 12
4. 45
5. None of these
Answer
Option 2 — 7
Explanation
For loop executes 3 times as length of smaller input is 3. Initial value of large is 4567.
1st Iteration
large = large[1:]
⇒ large = 567
(iv) Given a first input of 123 and a second input of 4567, what result is produced by Line 4?
1. 123
2. 4567
3. 7
4. 3
5. None of these
Answer
Option 1 — 123
Explanation
As length of 123 is less than length of 4567 so 123 is assigned to variable small and gets
printed in line 4.
Question 7a
Answer
Output
TesttseT
Explanation
The for loop reverses the input string and stores the reversed string in variable RS. After that
original string and reversed string are concatenated and printed.
Question 7b
Answer
The program gives an error at line RS = ch + 2 + RS. The operands to + are a mix of string
and integer which is not allowed in Python.
Question 8a
1. S = "PURA VIDA"
2. print(S[9] + S[9 : 15])
Answer
The error is in line 2. Length of string S is 9 so its indexes range for 0 to 8. S[9] is causing
error as we are trying to access out of bound index.
Question 8b
1. S = "PURA VIDA"
2. S1 = S[: 10] +S[10 :]
3. S2 = S[10] + S[-10]
Answer
The error is in line 3. Length of string S is 9 so its forward indexes range for 0 to 8 and
backwards indexes range from -1 to -9. S[10] and S[-10] are trying to access out of bound
indexes.
Question 8c
1. S = "PURA VIDA"
2. S1 = S * 2
3. S2 = S1[-19] + S1[-20]
4. S3 = S1[-19 :]
Answer
The error is in line 3. S1[-19] and S1[-20] are trying to access out of bound indexes.
Question 8d
1. S = "PURA VIDA"
2. S1 = S[: 5]
3. S2 = S[5 :]
4. S3 = S1 * S2
5. S4 = S2 + '3'
6. S5 = S1 + 3
Answer
The errors are in line 4 and line 6. Two strings cannot be multiplied. A string and an integer
cannot be added.
Question 9
Answer
(i) 3
The starting index of substring "never" in "whenever" is 3.
(ii) -1
Substring "what" is not present in "whenever".
Question 10
Answer
(i) '123-365-1319'
Question 11
Answer
1. print(S[:5])
2. print(S[8])
3. for a in range(-1, (-len(S) - 1), -1) :
print(S[a], end = '')
4. for a in range(-1, (-len(S) - 1), -2) :
print(S[a], end = '')
Question 1
Write a program to count the number of times a character occurs in the given string.
Solution
Output
Write a program which replaces all vowels in the string with '*'.
Solution
Output
Question 3
Write a program which reverses a string and stores the reversed string in a new string.
Solution
Output
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
Output
=====================================
Question 5
Sample
Solution
Output
=====================================
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
Solution
for ch in str :
if ch.isspace() :
spaceCount += 1
elif ch.isalnum() :
alnumCount += 1
print("Original Sentences:")
print(str)
print("Number of words =", (spaceCount + 1))
print("Number of characters =", (length + 1))
print("Alphanumeric Percentage =", alnumPercent)
Output
Question 7
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
Question 8
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
digitsStr = ''
digitsNum = 0;
for ch in str :
if ch.isdigit() :
digitsStr += ch
if digitsStr :
digitsNum = int(digitsStr)
Output
Enter an integer: 12
Enter the string: abc123
12 + 123 = 135
=====================================
Enter an integer: 20
Enter the string: a5b6c7
20 + 567 = 587
=====================================
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 :
PANDA
P n
y o
t h
Solution
small = str1
large = 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
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".
Solution
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
=====================================
=====================================
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
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
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
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
=====================================
Question 13
Write a program that inputs a line of text and prints out the count of vowels in it.
Solution
for ch in str :
lch = ch.lower()
if lch == 'a' \
or lch == 'e' \
or lch == 'i' \
or lch == 'o' \
or lch == 'u' :
count += 1
Output
Question 14
Write a program to input a line of text and print the biggest word (length wise) from it.
Solution
for w in words :
if len(w) > len(longWord) :
longWord = w
Output
Enter a string: TATA FOOTBALL ACADEMY WILL PLAY AGAINST MOHAN BAGAN
Longest Word = FOOTBALL
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
for w in words :
rw = ""
for ch in w :
rw = ch + rw
newStr += rw + " "
print(newStr)
Output