Practice Questions — Strings in Python
← Back to NotesTopic-Specific Questions
Question 1
Easy
What is the output of the following code?
s = "Python"
print(s[0])
print(s[-1])Index 0 is the first character. Index -1 is the last character.
PnQuestion 2
Easy
What is the output?
s = "Hello"
print(s[1:4])Slicing from index 1 up to (but not including) index 4.
ellQuestion 3
Easy
What is the output?
print("hello".upper())
print("WORLD".lower())upper() converts all characters to uppercase, lower() to lowercase.
HELLOworldQuestion 4
Easy
What is the output?
s = "Python"
print(len(s))
print(s[len(s)-1])len() returns the number of characters. The last valid index is len(s)-1.
6nQuestion 5
Easy
What is the output?
print("abc" * 3)
print("Hi" + "!" * 4)* repeats a string. + concatenates strings. * has higher precedence than +.
abcabcabcHi!!!!Question 6
Easy
What is the output?
s = " hello "
print(s.strip())
print(s.lstrip())
print(s.rstrip())strip() removes whitespace from both ends, lstrip() from left, rstrip() from right.
hellohello helloQuestion 7
Medium
What is the output?
s = "Programming"
print(s[::2])
print(s[1::2])Step 2 means take every second character. Starting from index 0 vs index 1 gives different results.
PormigrgamnQuestion 8
Medium
What is the output?
s = "abcdef"
print(s[-3:])
print(s[:-3])
print(s[-4:-1])Negative indices count from the end. -1 is the last character, -2 is second to last, etc.
defabccdeQuestion 9
Medium
What is the output?
s = "Hello World"
print(s.split())
print(s.split("o"))
print("l" in s)split() without arguments splits on whitespace. split("o") splits at every 'o'. 'in' checks membership.
['Hello', 'World']['Hell', ' W', 'rld']TrueQuestion 10
Medium
What is the output?
text = "Python is great"
print(text.find("is"))
print(text.find("was"))
print(text.count("t"))find() returns the starting index of the first match, or -1. count() counts non-overlapping occurrences.
7-12Question 11
Medium
What is the output?
s = "Hello"
print(s.replace("l", "L"))
print(s.replace("l", "L", 1))
print(s)replace() replaces all occurrences by default. The third argument limits replacements. The original is unchanged.
HeLLoHeLloHelloQuestion 12
Medium
What is the output?
name = "rohan"
print(name.capitalize())
print(name.title())
print("hello world python".title())capitalize() capitalizes only the first character. title() capitalizes the first letter of each word.
RohanRohanHello World PythonQuestion 13
Medium
What is the output?
words = ["Python", "is", "fun"]
result = " ".join(words)
print(result)
print("-".join("Hello"))join() uses the string as a separator between elements of the iterable.
Python is funH-e-l-l-oQuestion 14
Hard
What is the output?
s = "abcdef"
print(s[10:20])
print(s[-100:3])
print(s[2:100])Slicing with out-of-range indices does not raise errors. Python clips to available range.
(empty string)abccdefQuestion 15
Hard
What is the output?
s = "racecar"
print(s == s[::-1])
print(s[1:-1])
print(s[1:-1] == s[1:-1][::-1])[::-1] reverses a string. 'racecar' is a palindrome. What about the substring without the first and last character?
TrueacecaTrueQuestion 16
Hard
What is the output?
s = "Hello World"
print(s[::-1])
print(s[6::-1])
print(s[:5:-1])With negative step, the defaults change. Omitting start means start from the end. Omitting stop means go to the beginning.
dlroW olleHW olleHdlroWQuestion 17
Hard
What is the output?
s = "aabbaabb"
print(s.count("aa"))
print(s.count("ab"))
print(s.replace("aa", "x"))count() counts non-overlapping occurrences. replace() replaces all non-overlapping matches left to right.
22xbbxbbQuestion 18
Hard
What is the output?
print("42".zfill(5))
print("-42".zfill(5))
print("hello".center(11, "*"))
print("7".zfill(1))zfill() pads with zeros on the left. It handles negative signs specially. center() pads on both sides.
00042-0042***hello***7Mixed & Application Questions
Question 1
Easy
What is the output?
s = "Python"
print(s[0] + s[-1])s[0] is the first character, s[-1] is the last. + concatenates strings.
PnQuestion 2
Easy
What is the output?
name = "Meera"
for ch in name:
print(ch, end="-")A for loop iterates over each character. end="-" adds a hyphen after each print.
M-e-e-r-a-Question 3
Easy
What is the output?
print("Hello".startswith("He"))
print("Hello".endswith("lo"))
print("Hello".startswith("he"))startswith() and endswith() are case-sensitive.
TrueTrueFalseQuestion 4
Medium
What is the output?
s = "abcde"
result = ""
for i in range(len(s)-1, -1, -1):
result += s[i]
print(result)
print(result == s[::-1])The loop builds a reversed string character by character. Compare with slicing reversal.
edcbaTrueQuestion 5
Medium
What is the output?
s = "Hello World"
words = s.split()
print(words)
print(" ".join(words[::-1]))split() breaks into words. [::-1] reverses the list. join() combines them back.
['Hello', 'World']World HelloQuestion 6
Medium
What is the output?
x = 10
y = 3
print(f"{x} / {y} = {x/y:.2f}")
print(f"{x} // {y} = {x//y}")
print(f"{x} % {y} = {x%y}")f-strings can contain arithmetic expressions. :.2f formats to 2 decimal places.
10 / 3 = 3.3310 // 3 = 310 % 3 = 1Question 7
Medium
What is the output?
s = "Mississippi"
print(s.count("ss"))
print(s.count("i"))
print(s.replace("ss", "S"))count() counts non-overlapping occurrences from left to right.
24MiSiSippiQuestion 8
Hard
What is the output?
s = "Python"
print(s[1:5:2])
print(s[5:1:-2])
print(s[::3])s[start:stop:step] - with positive step, goes left to right. With negative step, goes right to left.
yhnhPhQuestion 9
Hard
What is the output?
print(ord("A"))
print(ord("a") - ord("A"))
print(chr(ord("A") + 3))
print(chr(ord("z") - 25))ord('A') is 65, ord('a') is 97. chr() converts a number back to a character.
6532DaQuestion 10
Hard
What is the output?
s = "aAbBcC"
uppers = ""
lowers = ""
for ch in s:
if ch.isupper():
uppers += ch
else:
lowers += ch
print(uppers)
print(lowers)isupper() returns True for uppercase letters, False otherwise.
ABCabcQuestion 11
Medium
What is the difference between
find() and index() when the substring is not found?One returns a special value, the other raises an exception.
find() returns -1 when the substring is not found. index() raises a ValueError when the substring is not found.Question 12
Medium
Why are strings called immutable in Python? What happens when you call a method like
upper() on a string?Think about whether the original string changes or a new one is created.
Strings are immutable because their content cannot be changed after creation. You cannot modify individual characters using indexing (e.g.,
s[0] = 'x' raises TypeError). When you call upper(), Python creates and returns a new string with all characters in uppercase. The original string remains unchanged.Question 13
Hard
What is the output?
s = "12345"
print(s.isdigit())
print(s.isalpha())
print("abc123".isalnum())
print("".isdigit())
print(" ".isalpha())These methods return True only if ALL characters match the condition AND the string is non-empty.
TrueFalseTrueFalseFalseMultiple Choice Questions
MCQ 1
Which of the following creates a valid string in Python?
Answer: D
D is correct. Python allows strings to be created with single quotes (A), double quotes (B), and triple quotes (C). All three produce valid string objects. Single and double quotes are interchangeable for single-line strings. Triple quotes support multi-line strings.
D is correct. Python allows strings to be created with single quotes (A), double quotes (B), and triple quotes (C). All three produce valid string objects. Single and double quotes are interchangeable for single-line strings. Triple quotes support multi-line strings.
MCQ 2
What does s[-1] return for a non-empty string s?
Answer: B
B is correct. Negative indexing starts from the end.
B is correct. Negative indexing starts from the end.
s[-1] always returns the last character of the string. s[-2] returns the second-to-last, and so on. Option A would be s[0]. Option C is wrong because -1 is a valid index for non-empty strings.MCQ 3
What is the result of 'Hello'[1:4]?
Answer: B
B is correct. Slicing
B is correct. Slicing
[1:4] includes indices 1, 2, 3 (stop index 4 is excluded). 'Hello'[1]='e', [2]='l', [3]='l', giving "ell". Option A starts from index 0. Option C would be [1:5]. Option D would be [0:4].MCQ 4
Which method removes whitespace from both ends of a string?
Answer: C
C is correct.
C is correct.
strip() removes leading and trailing whitespace. Python does not have clean() (A), trim() (B), or remove() (D) as string methods. Note: JavaScript uses trim(), but Python uses strip().MCQ 5
What does 'Python'[::-1] return?
Answer: B
B is correct. The slice
B is correct. The slice
[::-1] reverses the string. Starting from the end and going backwards through every character: n-o-h-t-y-P = "nohtyP". This is the standard Python idiom for reversing a string.MCQ 6
What is the output of 'Hello'.find('xyz')?
Answer: B
B is correct.
B is correct.
find() returns -1 when the substring is not found. It does NOT return None (C) or raise an error (D). index() would raise a ValueError, but find() returns -1 for the not-found case.MCQ 7
What does 'abc'.isalpha() return?
Answer: A
A is correct.
A is correct.
isalpha() returns True if all characters in the string are alphabetic (letters) and the string is non-empty. 'abc' contains only letters, so it returns True. It does not return the string itself (C) or a count (D).MCQ 8
What happens when you execute: s = 'Hello'; s[0] = 'h'?
Answer: C
C is correct. Strings are immutable in Python. You cannot assign to an index of a string. The statement
C is correct. Strings are immutable in Python. You cannot assign to an index of a string. The statement
s[0] = 'h' raises a TypeError: 'str' object does not support item assignment. To change the first character, create a new string: s = 'h' + s[1:].MCQ 9
What is the output of ' '.join(['a', 'b', 'c'])?
Answer: B
B is correct.
B is correct.
join() is called on the separator string (a single space here) and concatenates the list elements with that separator between them. So 'a', 'b', 'c' become "a b c". Option A would result from ''.join(). Option D would result from ', '.join().MCQ 10
Which of these is the correct way to format a float to 2 decimal places using an f-string?
Answer: B
B is correct. The format specifier
B is correct. The format specifier
:.2f means 2 digits after the decimal point, formatted as a float. Option A (:2f) sets minimum width to 2, not decimal places. Option C (:.2) would work for significant digits but not specifically for decimal places of a float. Option D is invalid syntax.MCQ 11
What does 'Hello World'.split() return?
Answer: B
B is correct.
B is correct.
split() with no arguments splits on whitespace and returns a list of words. It does NOT split into individual characters (C) or return a tuple (D). Option A would result from split('x') where 'x' is not in the string.MCQ 12
What is the output of 'aaa'.count('aa')?
Answer: A
A is correct.
A is correct.
count() counts non-overlapping occurrences. In 'aaa', after finding 'aa' starting at index 0, it moves past those 2 characters to index 2. From index 2, only one 'a' remains, which is not enough for 'aa'. So the count is 1. If it counted overlapping occurrences, it would be 2.MCQ 13
What is the output of 'abc' > 'abd'?
Answer: B
B is correct. String comparison is done character by character using Unicode values. 'a'=='a', 'b'=='b', then 'c' vs 'd': ord('c')=99, ord('d')=100. Since 99 < 100, 'abc' < 'abd', so 'abc' > 'abd' is False.
B is correct. String comparison is done character by character using Unicode values. 'a'=='a', 'b'=='b', then 'c' vs 'd': ord('c')=99, ord('d')=100. Since 99 < 100, 'abc' < 'abd', so 'abc' > 'abd' is False.
MCQ 14
What does 'Hello'[1:1] return?
Answer: C
C is correct. When start equals stop in a slice, the result is always an empty string because there are no indices between 1 and 1. No error is raised. The slice
C is correct. When start equals stop in a slice, the result is always an empty string because there are no indices between 1 and 1. No error is raised. The slice
[n:n] always returns an empty string for any valid or invalid n.MCQ 15
What is the output of '\n'.join(['a', 'b', 'c'])?
Answer: C
C is correct. The separator is
C is correct. The separator is
'\n' (newline character). join() places a newline between each element, resulting in a string where a, b, and c are on separate lines. When printed, it would display as three lines. Option A shows the escape sequence literally, not the actual output.MCQ 16
What does 'Python'.swapcase() return?
Answer: C
C is correct.
C is correct.
swapcase() converts uppercase letters to lowercase and lowercase letters to uppercase. 'P' becomes 'p', 'y' becomes 'Y', 't' becomes 'T', 'h' becomes 'H', 'o' becomes 'O', 'n' becomes 'N'. Result: "pYTHON".MCQ 17
What is the output of bool('') and bool(' ')?
Answer: C
C is correct. An empty string
C is correct. An empty string
'' is falsy in Python, so bool('') returns False. A string containing a space ' ' is non-empty (length 1), so bool(' ') returns True. Any non-empty string is truthy, even if it contains only whitespace.MCQ 18
What does the 'in' operator do with strings?
Answer: B
B is correct. The
B is correct. The
in operator checks for substring membership. 'lo' in 'Hello' returns True. It does not return an index (C) - that is what find() does. It does not insert anything (D) - strings are immutable.Coding Challenges
Challenge 1: Count Vowels and Consonants
EasyAarav has the string "Modern Age Coders". Write a program that counts and prints the number of vowels and consonants (ignore spaces and special characters).
Sample Input
(No input required)
Sample Output
Vowels: 6
Consonants: 9
Use a for loop. Consider both uppercase and lowercase letters.
text = "Modern Age Coders"
vowels = 0
consonants = 0
for ch in text:
if ch.lower() in "aeiou":
vowels += 1
elif ch.isalpha():
consonants += 1
print("Vowels:", vowels)
print("Consonants:", consonants)Challenge 2: Reverse Each Word
EasyGiven the string "Python is fun", reverse each word individually but keep the word order the same. Print the result.
Sample Input
(No input required)
Sample Output
nohtyP si nuf
Use split(), slicing, and join().
text = "Python is fun"
words = text.split()
reversed_words = []
for word in words:
reversed_words.append(word[::-1])
result = " ".join(reversed_words)
print(result)Challenge 3: Check Palindrome
EasyWrite a program that checks whether the string "madam" is a palindrome (reads the same forwards and backwards). Print the result.
Sample Input
(No input required)
Sample Output
madam is a palindrome
Use string slicing to reverse.
text = "madam"
if text == text[::-1]:
print(f"{text} is a palindrome")
else:
print(f"{text} is not a palindrome")Challenge 4: Title Case Converter
MediumPriya has the string "the quick brown fox jumps over the lazy dog". Write a program that converts it to title case WITHOUT using the built-in title() method. Capitalize the first letter of each word.
Sample Input
(No input required)
Sample Output
The Quick Brown Fox Jumps Over The Lazy Dog
Do not use title(). Use split(), string concatenation, and join().
text = "the quick brown fox jumps over the lazy dog"
words = text.split()
result = []
for word in words:
capitalized = word[0].upper() + word[1:]
result.append(capitalized)
print(" ".join(result))Challenge 5: Character Frequency Counter
MediumWrite a program that prints the frequency of each character in the string "banana" (excluding spaces). Print each character and its count on a separate line, without repeating characters.
Sample Input
(No input required)
Sample Output
b: 1
a: 3
n: 2
Use a loop. Track which characters you have already counted.
text = "banana"
counted = ""
for ch in text:
if ch not in counted:
print(f"{ch}: {text.count(ch)}")
counted += chChallenge 6: Caesar Cipher Encoder
MediumRohan wants to encode the message "HELLO" by shifting each letter 3 positions forward in the alphabet (A becomes D, B becomes E, ..., X becomes A, Y becomes B, Z becomes C). Write the encoder.
Sample Input
(No input required)
Sample Output
Encoded: KHOOR
Use ord() and chr(). Handle wrapping (Z + 1 = A).
message = "HELLO"
shift = 3
result = ""
for ch in message:
new_pos = (ord(ch) - ord('A') + shift) % 26
result += chr(ord('A') + new_pos)
print("Encoded:", result)Challenge 7: Remove Duplicate Characters
HardWrite a program that removes duplicate characters from the string "programming" while preserving the order of first occurrence. Print the result.
Sample Input
(No input required)
Sample Output
progamin
Use a loop. Track seen characters.
text = "programming"
result = ""
for ch in text:
if ch not in result:
result += ch
print(result)Challenge 8: Word Reverser Preserving Punctuation
HardAnanya has the string "Hello, World!". Write a program that reverses the order of words but keeps punctuation attached to its word. Expected output: "World! Hello,".
Sample Input
(No input required)
Sample Output
World! Hello,
Use split() and join(). Do not remove punctuation.
text = "Hello, World!"
words = text.split()
reversed_text = " ".join(words[::-1])
print(reversed_text)Challenge 9: String Compression
HardWrite a program that compresses the string "aaabbccddddee" by replacing consecutive duplicate characters with the character followed by its count. Single characters should not have a count.
Sample Input
(No input required)
Sample Output
a3b2c2d4e2
Use a loop. Handle the last group carefully.
text = "aaabbccddddee"
result = ""
i = 0
while i < len(text):
count = 1
while i + count < len(text) and text[i + count] == text[i]:
count += 1
if count > 1:
result += text[i] + str(count)
else:
result += text[i]
i += count
print(result)Need to Review the Concepts?
Go back to the detailed notes for this chapter.
Read Chapter NotesWant to learn Python with a live mentor?
Explore our Python course