How to replace characters in a string in Python?

If you are looking for replacing instances of a character in a string, Python has a built-in replace() method which does the task for you.

The replace method replaces each matching occurrence of the old characters/substring with the new characters/substring.

Syntax : 

string.replace(old, new, count)

Parameters : 

  • old – character or substring you want to replace. 
  • new – a new character or substring which would replace the old substring.
  • count (optional)–  the number of times you want to replace the old substring with the new substring 

Return Value

This method returns a copy of the string, where the old substring is replaced with a new one, keeping the original string unchanged. If the old string is not found, the copy of the original string is returned.

Example 1 – Replace all the instances of a character in a given string

# replace all the characters in a string
sample_text = 'All the, commas, will, be, replaced  by empty string, in this,, sentence,'
print(sample_text.replace(',', ''))

Output

All the commas will be replaced  by empty string in this sentence

Example 2 – Replace all the instances of a substring in a given string


# replace the old substring with new substring
sample_text2 = 'This is a wrong sentence'
print(sample_text2.replace('wrong', 'correct'))

Output

This is a correct sentence

Example 3 – Replace only one instances of a substring in a given string


# replace substring of only one occurence
sample_text3 = 'int, string, bool, byte, string, float,  bit, string'
print(sample_text3.replace('string', 'char',1))

Output

int, char, bool, byte, string, float,  bit, string

Example 4 – Replace character in string at index

#  Replace character in string at index 
sample_text4 = 'Europx'
new_text ='e'
print(sample_text4[:5] + new_text + sample_text4[5+1:])

Output

Europe
Leave a Reply

Your email address will not be published.

Sign Up for Our Newsletters

Get notified of the best deals on our WordPress themes.

You May Also Like
Python List Extend()

Python List extend()

Table of Contents Hide Syntax of List extend() extend() ParametersReturn Value from List extend()Difference between append() and extend() method in PythonExample 1: How to use List extend() MethodExample 2: Add Elements…
View Post
Python String Zfill()

Python String zfill()

Table of Contents Hide zfill() Syntaxzfill() Parameterszfill() Return ValueExample 1: How zfill() works in Python?Example 2: zfill() in case of Sign Prefix The Python String zfill() method is a built-in…
View Post
How To Copy A File In Python

How to Copy a File in Python?

Table of Contents Hide Modules to copy a file in Python shutil module top copy a file in Pythoncopy() copy2() copyfile() copyfileobj()os module to copy a file in Pythonpopen() system() subprocess…
View Post