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

Greetings, I'm Devendra Dode, a full-stack developer, entrepreneur, and the proud owner of Tutsmake.com. My passion lies in crafting informative tutorials and offering valuable tips to assist fellow developers on their coding journey. Within my content, I cover a spectrum of technologies, including 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. Whether you're starting out or looking for advanced examples, I provide step-by-step guides and practical demonstrations to make your learning experience seamless. Let's explore the diverse realms of coding together.

Leave a Reply

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