Computer Science · Ch 8 — Strings
Handling Strings
Handling Strings
This section brings the whole chapter together: user-defined functions that perform practical operations on strings. Each program below defines a function, reads input from the user, calls the function, and prints the result. Together they exercise traversal, membership testing, negative indexing, concatenation and comparison of characters.
Program 8-1 — Count occurrences of a character
Task: a user-defined function that counts how many times a character (passed as an argument) occurs in a given string.
The function traverses the string with a for loop and increments a counter each time the current character equals the one being searched for.
# Function to count how many times a character occurs in a string
def charCount(ch, st):
count = 0
for character in st:
if character == ch:
count += 1
return count
# end of function
st = input("Enter a string: ")
ch = input("Enter the character to be searched: ")
count = charCount(ch, st)
print("Number of times character", ch, "occurs in the string is:", count)
Enter a string: Today is a Holiday
Enter the character to be searched: a
Number of times character a occurs in the string is: 3
Program 8-2 — Replace all vowels with *
Task: a user-defined function taking a string as parameter that replaces every vowel in it with the character '*'.
Because strings are immutable (Section 8.2.2), the function cannot overwrite characters in place. Instead it builds a new string: starting from an empty string, it appends either '*' (if the current character is a vowel) or the character itself. The vowel test uses the membership operator in against the string 'aeiouAEIOU', which covers both cases at once.
# Function to replace all vowels in the string with '*'
def replaceVowel(st):
newstr = '' # create an empty string
for character in st:
if character in 'aeiouAEIOU': # is it a vowel?
newstr += '*' # replace vowel with *
else:
newstr += character
return newstr
# end of function
st = input("Enter a String: ")
st1 = replaceVowel(st)
print("The original String is:", st)
print("The modified String is:", st1)
Enter a String: Hello World
The original String is: Hello World
The modified String is: H*ll* W*rld
Note that the original string survives unchanged — the function returned a fresh string.
Program 8-3 — Print a string in reverse (no new string)
Task: input a string and print it in reverse order without creating a new string.
The trick is negative indexing: range(-1, -len(st)-1, -1) generates the indices -1, -2, ..., -len(st) — i.e., the characters from the rightmost to the leftmost. Printing each with end='' displays the reversed text without ever building a second string.
# Program to display a string in reverse order
st = input("Enter a string: ")
for i in range(-1, -len(st) - 1, -1):
print(st[i], end='')
Enter a string: Hello World
dlroW olleH
Program 8-4 — Reverse a string into a new string
Task: a user-defined function that reverses the string passed as parameter and stores the reversed string in a new string.
The traversal logic is the same negative-index range as Program 8-3, but instead of printing each character the function concatenates it onto a new string, which it then returns.
# Function to reverse a string
def reverseString(st):
newstr = '' # create a new string
length = len(st)
for i in range(-1, -length - 1, -1):
newstr += st[i]
return newstr
# end of function
st = input("Enter a String: ")
st1 = reverseString(st)
print("The original String is:", st)
print("The reversed String is:", st1)
Enter a String: Hello World
The original String is: Hello World
The reversed String is: dlroW olleH
Program 8-5 — Check whether a string is a palindrome
Task: a user-defined function to check if a string is a palindrome — a string that reads the same backwards as forwards (for example, kanak).
The function uses two indices moving towards each other: i starts at the first character and j at the last. At each step it compares st[i] with st[j]; the moment any pair differs, the string cannot be a palindrome and the function returns False immediately. If the two indices cross without finding a mismatch, every pair matched and the function returns True.