770
In this article we show 2 ways of replacing characters in a string using python
Example 1
This first example lets the user enter a test string, a character to replace and the new character
We use the built in string replace function to replace one character with a new character.
# Replace Characters in a String string1 = input("Please Enter your String : ") character1 = input("Please Enter your Own Character : ") newcharacter1 = input("Please Enter the New Character : ") string2 = string1.replace(character1, newcharacter1) print("\nOriginal String : ", string1) print("Modified String : ", string2)
You will see the following
>>> %Run replacecharstring1.py Please Enter your String : This is a test sentence Please Enter your Own Character : e Please Enter the New Character : o Original String : This is a test sentence Modified String : This is a tost sontonco
Example 2
# Replace a Character in a String Using a For Loop # User Input string1 = input("Please Enter your String : ") character1 = input("Please Enter your Own Character : ") newcharacter1 = input("Please Enter the New Character : ") string2 = '' for i in range(len(string1)): if(string1[i] == character1): string2 = string2 + newcharacter1 else: string2 = string2 + string1[i] print("Original String : ", string1) print("\nModified String : ", string2)
You will see the following
>>> %Run replacecharstring2.py Please Enter your String : This is a test sentence Please Enter your Own Character : e Please Enter the New Character : o Original String : This is a test sentence Modified String : This is a tost sontonco
Link
This is in our github repository
https://github.com/programmershelp/maxpython/tree/main/code%20example/String%20examples