Python Program To Replace Characters In A String
Chapter:
Python
Last Updated:
03-06-2023 13:05:41 UTC
Program:
/* ............... START ............... */
def replace_characters(string, old_char, new_char):
# Split the string into a list of characters
characters = list(string)
# Iterate through the characters and replace the old character with the new character
for i in range(len(characters)):
if characters[i] == old_char:
characters[i] = new_char
# Join the characters back into a string
new_string = ''.join(characters)
return new_string
# Example usage
input_string = input("Enter a string: ")
old_character = input("Enter the character to replace: ")
new_character = input("Enter the new character: ")
result = replace_characters(input_string, old_character, new_character)
print("Modified string:", result)
/* ............... END ............... */
Output
Enter a string: Hello World!
Enter the character to replace: o
Enter the new character: x
Modified string: Hellx Wxrld!
In this example, the user entered the string "Hello World!", and they wanted to replace the
character 'o' with 'x'. The program then replaced all occurrences of 'o' with 'x' in the
string and returned the modified string "Hellx Wxrld!" as the output.
Notes:
-
In this program, the replace_characters function takes three parameters: string (the original string), old_char (the character to be replaced), and new_char (the new character to replace the old character with). It iterates through each character in the string, checks if it matches the old_char, and if so, replaces it with the new_char. Finally, it joins the modified characters back into a string and returns the result.
- You can run this program and provide the required inputs to replace characters in a given string.