Python string exercises with solution

Anything enclosed inside the quotation marks is called a string in python. It can be in either single quotes, double quotes, or triple quotes. Strings are immutable however, it supports indexing and slicing in addition to concatenation and repetition. The string has a maximum method compared to other data types. It supports 45 methods in total.

Related article:

  1. String data type
  2. String methods

Here, we have five string exercises with solutions for you. It is supposed to give you some idea of how to use string methods and implement indexing and slicing on it.

1. Traffic signals

Write a python program to replicate the traffic light signals. Your program should implement string methods whereby “GREEN”, “Green”, “green” or any color should be read the same until and unless there is a difference in spelling. The program should work perfectly for the following light signals:

  1. RED – Stop the car.
  2. YELLOW – Slow down and be ready to stop.
  3. GREEN – Go.
  4. Other color signals – Unrecognized signal.

Source Code:

signal = input("Enter the signal:").upper()

if signal == "GREEN":
    print("Go!")

elif signal == "RED":
    print("STOP!")

elif signal == "YELLOW":
    print("SLOW DOWN!")

else:
    print("Unrecgonized signal!")

Expected Output:

Enter the signal:green
Go!
>>> 
Enter the signal:GREEN
Go!
>>> 
Enter the signal:Green
Go!
>>> 
Enter the signal:Red
STOP!
2. Extract Initials

Write a python program that asks the user for their first and last name and then prints their initials.

Source code:

fname = input("Enter your first name:").title()
lname = input("Enter your last name: ").title()

name = fname + lname

print(f"Hello {name} your initials is {fname[0]}.{lname[0]}")

Expected output:

Enter your first name:sonam 
Enter your last name: dorji
Hello Sonam Dorji your initials is S.D
3. Replace

Write a function called replace_at_index that takes three arguments – a string, an integer (representing an index), and a string. Return a string that is the same as the first string, except with the character at the specified index replaced by the second string.
Ask the user for some text, which index to replace, and what to replace that index with (in that order!).
Print out the result of calling your function.

Source code;

def replace_at_index(initial, i, final):
    print("\nFinal Result:")
    print("Word:", initial)
    print(word[index_replace], "will be replaced by ",character, "at index ", i )
    final_word = initial[:i] + character + initial[i+1:]
    print("Final result: ",final_word)

word = input("Enter a word or Phrase:")
index_replace = int(input("Index you want to replace at:"))
character = input("Enter a character you want to replace:")

replace_at_index(word,index_replace, character )

Expected Output:

Enter a word or Phrase:Medication
Index you want to replace at:4
Enter a character you want to replace:t

Final Result:
Word: Medication
c will be replaced by  t at index  4
Final result:  Meditation
4. Count

Write a function called count_occurrences that takes two strings. The second string should only be one character long. The function should return how many times the second string occurs in the first string.
You will need:
A function declaration for the function count_occurrences, with parameters.

Ask the user to input both strings (first the word, and then the letter). Then enter the two strings as parameters to your function.

Source code:

def count_occurrences(first, second):
    count = 0
    for letter in first:
        if letter == second:
            count = count + 1
    return count

word = input("Enter a word: ")
character = input("Enter a letter: ")
print(f"A letter {character} appeared {count_occurrences(word, character)} times in the word {word}")

Expected Output:

Enter a word: Python Programming
Enter a letter: n
A letter n appeared 2 times in the word Python Programming
5. Remove

Write a function called remove_all_from_string that takes two strings, and returns a copy of the first string with all instances of the second string removed. This time, the second string may be any length, including 0. Test your function on the strings “bananas” and “na”. Print the result, which should be: bas

You must use:

Source code:

def remove_all_from_string(s, to_remove):
    if not to_remove:
        return s
    
    while True:
        index = s.find(to_remove)
        if index == -1:
            return s
        s = s[:index] + s[index + len(to_remove):]

word = input("Enter a word:")
character_to_rmv = input("Enter a character:")
print(remove_all_from_string(word,character_to_rmv ))

Expected Outcome:

Enter a word:bananas
Enter a character:na
bas