How to replace a character in a string in python

How to replace a character in a string in python

Replace a character in string python; In this tutorial, you will learn how to replace a character in a string at index and without index in python

As well as, you will learn in detail about python string replace() methods syntax, parameters and return value etc.

How to replace a character in a string in python

The python replace() method returns a copy of the string where all occurrences of a substring are replaced with another substring.

The syntax of replace() is:

str.replace(old, new [, count]) 

parameters of replace() method

The replace() method can take maximum of three parameters:

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

If count is not specified, replace() method replaces all occurrences of the old substring with the new substring.

Return Value from replace()

The replace() method returns a copy of the string where old substring is replaced with the new substring. The original string is unchanged.

If the old substring is not found, it returns the copy of the original string.

Example 1: python replace multiple characters in string

string = 'python is good programming language. Python is best programming language'

'''occurences of 'python' is replaced'''
print(string.replace('python', "The python"))

Output

The python is good programming language. Python is best programming language

Example 2: Replace the two first occurrence of the string in python

txt = "one one was a race horse, two two was one too."

x = txt.replace("one", "three", 2)

print(x)

Output

 three three was a race horse, two two was one too

Recommended Python Tutorials

AuthorAdmin

My name is Devendra Dode. I am a full-stack developer, entrepreneur, and owner of Tutsmake.com. I like writing tutorials and tips that can help other developers. I share tutorials of PHP, Python, Javascript, JQuery, Laravel, Livewire, Codeigniter, Node JS, Express JS, Vue JS, Angular JS, React Js, MySQL, MongoDB, REST APIs, Windows, Xampp, Linux, Ubuntu, Amazon AWS, Composer, SEO, WordPress, SSL and Bootstrap from a starting stage. As well as demo example.

Leave a Reply

Your email address will not be published. Required fields are marked *