This Python program replaces all occurrences of the character ‘a’ with ‘$’ in a given string.
Write a Python program that replaces all occurrences of the letter ‘a’ with a dollar sign (‘$’) in a given string.
Your program should take a string as input and return the modified string where all occurrences of ‘a’ are replaced with ‘$’. The program should preserve the original case of the letters.
Example: Input: “apple banana avocado” Output: “$pple b$n$n$ $voc$do”
- The input string can contain uppercase and lowercase letters.
- If the input string does not contain any ‘a’ characters, the program should return the original string unchanged.
- The program should handle strings of any length.
- The program should be case-sensitive, meaning that ‘A’ should not be replaced with ‘$’.
You can implement this program using the
replace() method in Python, which allows you to replace one substring with another within a string.
Python Program to Replace All Occurrences of ‘a’ with $ in a String
def replace_characters(string): replaced_string = string.replace('a', '$') return replaced_string # Example usage input_string = 'apple banana avocado' output_string = replace_characters(input_string) print(output_string)
How it Works
The Python program works by utilizing the
replace() method to replace all occurrences of the letter ‘a’ with a dollar sign (‘$’) in the given string. Here’s how it works:
- The program defines a function called
replace_charactersthat takes a string as input.
- Inside the function, the
replace()method is used on the input string to replace all occurrences of ‘a’ with ‘$’. The modified string is assigned to the variable
- The modified string
replaced_stringis then returned as the output of the function.
- Outside the function, an example input string is provided and assigned to the variable
replace_charactersfunction is called with
input_stringas the argument, and the returned value is assigned to the variable
- Finally, the modified string
output_stringis printed to the console.
replace() method is a built-in string method in Python that takes two arguments: the substring to be replaced and the substring to replace it with. In this case, ‘a’ is specified as the substring to be replaced, and ‘$’ is specified as the substring to replace it with.
replace() method scans the input string and replaces all occurrences of ‘a’ with ‘$’, creating a new modified string. The original string remains unchanged. The function
replace_characters encapsulates this logic and allows for reusability.