Web development and Tech news Blog site. WEBISFREE.com

HOME > python

Python text character replacement method, substitute method, replace()

Last Modified : 04 Mar, 2023 / Created : 04 Mar, 2023
545
View Count

The following is a summary of the simplest and most important method for character substitution (replace) in Python, along with its contents. Let's briefly explore it below.



# How to replace or change characters in Python language


In Python, there is a built-in function called replace() to replace characters. The usage is very simple, but let's first take a look at the syntax.

String.replace(originStr, replaceStr, maxCount)


The replace() function used in strings takes three arguments and is commonly used as shown below.

originStr // <Required> Specify the text to find as a required value.
replaceStr // <Required> Specify the text to be changed to a required value.
maxCount //  <Optional> Decide on how many maximum values ​​to change that match the selected value.

The first and second values here are mandatory, while the others represent optional values. The third value here is an option; if no value is inputted, all values will be changed. Now, let's create a simple example below.


! python replace() function examples


Let's try changing some characters to different values if the variable sitename exists.
>>> sitename = 'webisfree'
>>> sitename.replace('free', 'world')

// Result
'webisworld'

You can see that 'free' text has been changed to 'world'. Note that the value of 'sitename' is not changed. If you want to modify the original variable, you need to declare a new one as shown below.
>>> sitename = sitename.replace('free', 'world')

Now the variables have been changed together.


! If there are multiple equal values and you only want to change a certain number of them, maxCount


When using the third option value, you can change only as many times as you want among the matching strings. This time, we want to replace "e" with "x". Let's try changing "x" once, twice, and finally three times. We will execute it by adding the third argument from 1 to 3.
>>> sitename = 'webisfree'
>>> sitename.replace('e', 'x', 1)
>>> sitename.replace('e', 'x', 2)
>>> sitename.replace('e', 'x', 3)

// Result
'wxbisfree'
'wxbisfrxe'
'wxbisfrxx'

I checked the output result.


[ Reference ] What happens if the value of the third argument is set to -1?
You can set the value of maxCount to -1. In this case, all results will be changed, and it will bring the same result as the Default value that is not specified.


We have briefly learned about how to manipulate and replace strings in Python up to this point.

Perhaps you're looking for the following text as well?

Previous

How to convert lower case to upper case in Python

Previous

Print all keys in a python dictionary type