Class 12th Python String Questions with Code and Output
1. Reverse a string using slicing
Code:
s = "ComputerScience"
print(s[::-1])
Output: ecneicSretupmoC
2. Count the number of vowels in a string
Code:
s = "Beautiful Day"
count = 0
for char in s.lower():
if char in "aeiou":
count += 1
print("Vowel Count:", count)
Output: Vowel Count: 6
3. Check if a string is a palindrome
Code:
s = "madam"
if s == s[::-1]:
print("Palindrome")
else:
print("Not a Palindrome")
Output: Palindrome
4. Replace spaces with hyphens
Code:
s = "Python is fun"
print(s.replace(" ", "-"))
Output: Python-is-fun
5. Find the longest word in a sentence
Code:
sentence = "Python is a powerful language"
words = sentence.split()
longest = max(words, key=len)
print("Longest word:", longest)
Output: Longest word: powerful
6. Count frequency of each character
Code:
s = "banana"
freq = {}
for char in s:
freq[char] = freq.get(char, 0) + 1
print(freq)
Output: {'b': 1, 'a': 3, 'n': 2}
7. Swap the case of a string
Code:
s = "HeLLo WorLD"
print(s.swapcase())
Output: hEllO wORld
8. Print characters at even indices
Code:
s = "Programming"
print(s[::2])
Output: Pormig
9. Remove all punctuation from a string
Code:
import string
s = "Hello, World! Welcome to Python."
cleaned = "".join(char for char in s if char not in string.punctuation)
print(cleaned)
Output: Hello World Welcome to Python
10. Count words in a string
Code:
s = "Hello world this is Python"
print("Word Count:", len(s.split()))
Output: Word Count: 5