Home ยป Replace Characters in a String in python

Replace Characters in a String in python

Java SE 11 Developer (Upgrade) [1Z0-817]
Java SE 11 Programmer II [1Z0-816] Practice Tests
Java SE 11 Programmer I [1Z0-815] Practice Tests
Spring Framework Basics Video Course
1 Year Subscription
Oracle Java Certification

In this article we show 2 ways of replacing characters in a string using python

Table of Contents

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

You may also like

Leave a Comment

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More