DEV Community

Srinivas for ItsMyCode

Posted on • Originally published at itsmycode.com on

How to replace characters in a string in Python?

ItsMyCode |

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(',', ''))

Enter fullscreen mode Exit fullscreen mode

Output

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

Enter fullscreen mode Exit fullscreen mode

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'))

Enter fullscreen mode Exit fullscreen mode

Output

This is a correct sentence
Enter fullscreen mode Exit fullscreen mode

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))
Enter fullscreen mode Exit fullscreen mode

Output

int, char, bool, byte, string, float, bit, string
Enter fullscreen mode Exit fullscreen mode

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:])

Enter fullscreen mode Exit fullscreen mode

Output

Europe
Enter fullscreen mode Exit fullscreen mode

The post How to replace characters in a string in Python? appeared first on ItsMyCode.

Discussion (0)