Question 01 of 04

Menu-Driven String Operations using Built-in Functions

Write a menu-driven Python program to perform the following operations on strings using string built-in functions: a. Find the frequency of a character in a string. b. Replace a character by another character in a string. c. Remove the first occurrence of a character from a string. d. Remove all occurrences of a character from a string.

C++
def string_menu():
    text = input("Enter the source string: ")
    
    while True:
        print("\n" + "=" * 45)
        print("          STRING OPERATIONS MENU")
        print("=" * 45)
        print("1. Find frequency of a character")
        print("2. Replace a character with another character")
        print("3. Remove the FIRST occurrence of a character")
        print("4. Remove ALL occurrences of a character")
        print("5. Enter a new string")
        print("6. Exit")
        print("=" * 45)
        
        choice = input("Enter your choice (1-6): ").strip()
        
        if choice == '1':
            ch = input("Enter character to find frequency of: ")
            freq = text.count(ch)
            print(f"Frequency of '{ch}' in "{text}": {freq}")
            
        elif choice == '2':
            old_ch = input("Enter character to replace: ")
            new_ch = input("Enter replacement character: ")
            replaced = text.replace(old_ch, new_ch)
            print(f"Modified string: "{replaced}"")
            
        elif choice == '3':
            ch = input("Enter character to remove first occurrence of: ")
            # replace with maxcount=1 removes only the first occurrence
            removed_first = text.replace(ch, "", 1)
            print(f"After removing first occurrence of '{ch}': "{removed_first}"")
            
        elif choice == '4':
            ch = input("Enter character to remove all occurrences of: ")
            removed_all = text.replace(ch, "")
            print(f"After removing all occurrences of '{ch}': "{removed_all}"")
            
        elif choice == '5':
            text = input("Enter the new source string: ")
            
        elif choice == '6':
            print("Exiting string menu program. Goodbye!")
            break
        else:
            print("Invalid choice! Please choose between 1 and 6.")

if __name__ == "__main__":
    string_menu()
Question 1 of 4