Practice Problems with Solutions
1. Accessing Characters by Index
Problem:
Write a program that takes a string "Python" and prints:
- The first character
- The last character
- The third character
Solution:
s = "Python"
print("First character:", s[0])
print("Last character:", s[-1])
print("Third character:", s[2])
Explanation:
- s[0] accesses the first character because indexing starts at 0.
- s[-1] accesses the last character (negative index).
- s[2] gives the third character (P=0, y=1, t=2).
Output:
First character: P
Last character: n
Third character: t
2. Extracting a Substring Using Slicing
Problem:
Given "PythonProgramming", extract:
- "Python"
- "Programming"
- Reverse the entire string.
Solution:
s = "PythonProgramming"
print(s[0:6]) # 'Python'
print(s[6:]) # 'Programming'
print(s[::-1]) # reversed
Explanation:
- s[0:6] → starts at index 0, ends before 6
- s[6:] → starts from index 6 till end
- [::-1] → reverses because step = -1
3. Count the Occurrence of a Character
Problem:
Count how many times the letter 'o' appears in "Hello World".
Solution:
s = "Hello World"
count = s.count('o')
print("Occurrences of 'o':", count)
Explanation:
.count('o') counts the number of times 'o' occurs in the string.
Output:
Occurrences of 'o': 2
4. Check if a Word Exists in a Sentence
Problem:
Check if the word "Python" is present in "I am learning Python programming".
Solution:
text = "I am learning Python programming"
if "Python" in text:
print("Yes, 'Python' is present.")
else:
print("No, 'Python' is not present.")
Explanation:
The in operator returns True if the substring exists.
Output:
Yes, 'Python' is present.
5. Replace a Word in a String
Problem:
Replace the word "bad" with "good" in "This is a bad example".
Solution:
s = "This is a bad example"
result = s.replace("bad", "good")
print(result)
Explanation:
.replace(old, new) substitutes all occurrences of the old word with the new one.
Output:
This is a good example
6. Remove Whitespaces from Both Ends
Problem:
Remove leading and trailing spaces from " Hello World ".
Solution:
s = " Hello World "
clean = s.strip()
print(clean)
Explanation:
.strip() removes whitespace from both sides but not in between words.
Output:
Hello World
7. Convert Case
Problem:
Convert "python programming" into:
- All uppercase
- Title case
- Capitalize only first letter
Solution:
s = "python programming"
print(s.upper())
print(s.title())
print(s.capitalize())
Explanation:
- upper() → converts all letters to uppercase
- title() → capitalizes first letter of each word
- capitalize() → only first word gets capitalized
Output:
PYTHON PROGRAMMING
Python Programming
Python programming
8. Count Vowels in a String
Problem:
Write a program that counts how many vowels (a, e, i, o, u) are present in "Automation".
Solution:
s = "Automation".lower()
count = 0
for ch in s:
if ch in "aeiou":
count += 1
print("Number of vowels:", count)
Explanation:
- Convert to lowercase for uniformity.
- Loop through each character and check if it’s a vowel.
- Increment a counter when a vowel is found.
Output:
Number of vowels: 6
9. Check if String is Palindrome
Problem:
A palindrome reads the same backward as forward (e.g., "madam").
Check if a given string is a palindrome.
Solution:
s = "madam"
if s == s[::-1]:
print("Palindrome")
else:
print("Not a palindrome")
Explanation:
[::-1] reverses the string.
If the reversed version equals the original, it’s a palindrome.
Output:
Palindrome
10. Join a List of Words into a Sentence
Problem:
Join the list ["Python", "is", "fun"] into a single string with spaces.
Solution:
words = ["Python", "is", "fun"]
sentence = " ".join(words)
print(sentence)
Explanation:
join() combines elements of a list into a single string separated by the given character (space here).
Output:
Python is fun
11. Extract Digits from a String
Problem:
From "abc123xyz", extract only numbers.
Solution:
s = "abc123xyz"
digits = ""
for ch in s:
if ch.isdigit():
digits += ch
print(digits)
Explanation:
isdigit() checks if a character is a number.
We accumulate those into a new string.
Output:
123
12. Remove All Punctuation
Problem:
Remove all punctuation marks from "Hello!!! Are you fine?".
Solution:
import string
s = "Hello!!! Are you fine?"
clean = ""
for ch in s:
if ch not in string.punctuation:
clean += ch
print(clean)
Explanation:
string.punctuation contains all common punctuation marks.
We build a new string excluding those.
Output:
Hello Are you fine
13. Find the Longest Word in a Sentence
Problem:
Given "Python is an amazing programming language", find the longest word.
Solution:
sentence = "Python is an amazing programming language"
words = sentence.split()
longest = max(words, key=len)
print("Longest word:", longest)
Explanation:
- split() separates words.
- max() with key=len finds the word with the largest length.
Output:
Longest word: programming
14. Count Frequency of Each Character
Problem:
Count how many times each character appears in "banana".
Solution:
s = "banana"
freq = {}
for ch in s:
freq[ch] = freq.get(ch, 0) + 1
print(freq)
Explanation:
- dict.get(ch, 0) initializes count to 0 if key doesn’t exist.
- Each time a character appears, its count increases by 1.
Output:
{'b': 1, 'a': 3, 'n': 2}
15. String Formatting Practice
Problem:
Use f-strings to print the following sentence dynamically:
“Student Alice scored 85 marks in Math.”
Solution:
name = "Alice"
score = 85
subject = "Math"
print(f"Student {name} scored {score} marks in {subject}.")
Explanation:
f-strings let you embed variables directly using {} placeholders.
Output:
Student Alice scored 85 marks in Math.
16. Replace Vowels with ‘*’
Problem:
Replace every vowel in "education" with an asterisk *.
Solution:
s = "education"
result = ""
for ch in s:
if ch.lower() in "aeiou":
result += "*"
else:
result += ch
print(result)
Explanation:
For each character, check if it’s a vowel. Replace it with * if true.
Output:
*d*c*t**n
17. Check If Two Strings are Anagrams
Problem:
Two strings are anagrams if they have the same letters in a different order.
Example: "listen" and "silent".
Solution:
s1 = "listen"
s2 = "silent"
if sorted(s1) == sorted(s2):
print("Anagrams")
else:
print("Not anagrams")
Explanation:
Sorting arranges letters alphabetically.
If sorted results match, the strings contain the same letters.
Output:
Anagrams
18. Display Only Unique Characters
Problem:
Print only characters that appear once in "mississippi".
Solution:
s = "mississippi"
for ch in s:
if s.count(ch) == 1:
print(ch, end="")
Explanation:
count(ch) returns how many times ch appears.
We print only those with count = 1.
Output:
m
19. Capitalize the First Letter of Each Word Without Using title()
Problem:
Convert "hello world this is python" → "Hello World This Is Python"
Solution:
s = "hello world this is python"
words = s.split()
result = " ".join(word[0].upper() + word[1:] for word in words)
print(result)
Explanation:
- split() divides sentence into words.
- Each word is reconstructed with first letter in uppercase.
- join() recombines them with spaces.
Output:
Hello World This Is Python
20. Reverse Each Word in a Sentence
Problem:
Input: "Python is fun"
Output: "nohtyP si nuf"
Solution:
sentence = "Python is fun"
words = sentence.split()
reversed_words = [word[::-1] for word in words]
result = " ".join(reversed_words)
print(result)
Explanation:
- Split sentence into words.
- Reverse each word individually using slicing.
- Join the reversed words with spaces.
Output:
nohtyP si nuf
