String programs for practicals
Part of the free LogicWiz Python course, Module 4: Strings. The examples and practice run in the app.
Open any CBSE practical file and you'll find the same programs: count the vowels, check a palindrome, count capitals and digits, reverse the words, find the longest word. They are all one loop pattern in different clothes.
You'll learn to
- Loop over a string by character and by index
- Count vowels, cases, digits and other characters
- Check palindromes with slicing and with two pointers
- Work with words: count, reverse, find the longest
Learn
Two ways to walk through a string
for ch in s:gives you each character. Use it most of the time.for i in range(len(s)):gives you each index, ands[i]is the character. Use it when you need the position (or the character next to it).
The pattern behind every counting program: start a counter at 0, loop, if the character is the kind you want, add 1, return the counter.
Characters vs indexes
s = "Riya"
for ch in s:
print(ch, end=" ")
print()
for i in range(len(s)):
print(i, s[i])
The counting pattern
def counts(text):
v = up = lo = dg = 0
for ch in text:
if ch.lower() in "aeiou":
v += 1
if ch.isupper():
up += 1
elif ch.islower():
lo += 1
elif ch.isdigit():
dg += 1
return v, up, lo, dg
print(counts("Board Exam 2027"))
The vowel check is a separate if, because a vowel is also upper or lower. ch.lower() in "aeiou" catches both A and a.
Palindrome, the slicing way
def is_palindrome(s):
s = s.lower().replace(" ", "")
return s == s[::-1]
print(is_palindrome("Malayalam"))
print(is_palindrome("Nitin"))
print(is_palindrome("Never odd or even"))
print(is_palindrome("Python"))
Palindrome, the two-pointer way
def is_pal(s):
i = 0
j = len(s) - 1
while i < j:
if s[i] != s[j]:
return False
i += 1
j -= 1
return True
print(is_pal("level"), is_pal("lever"))
Compare the two ends and move inwards. Stop at the first mismatch. Only after the loop finishes can you say True. Interviewers ask for this version because it uses no extra string.
The classic bug: return True inside the loop. Then the function answers after checking only the first pair: "abca" looks like a palindrome because a == a. A return True belongs after the loop, once every pair has passed.
Working with words
line = "the quick brown fox"
words = line.split()
print(len(words), "words")
print(" ".join(words[::-1]))
flipped = ""
longest = ""
for w in words:
flipped += w[::-1] + " "
if len(w) > len(longest):
longest = w
print(flipped.strip())
print("longest:", longest)
A list slices just like a string, so words[::-1] reverses the word order. Using > (not >=) keeps the first longest word when two tie.
CBSE Class 11 and 12 practicals list these exact programs: count vowels / consonants / upper / lower / digits, check a palindrome, count words, convert the case of each character. Board output questions build a new string in a loop (new = new + …). Trace them in a table: one row per character, one column for the new string.
In one line
Every string program is: loop over the characters, test each with in or an is… method, update a counter or build a new string; return True only after the loop.