Python String replace() Method

The Python replace() method is a string method that replaces a specified phrase with another specified phrase. It has the following syntax:

string.replace(oldvalue, newvalue, count)

where oldvalue is the substring to be replaced, newvalue is the new substring that will replace it, and count is an optional parameter that specifies how many occurrences of oldvalue to replace (default is all occurrences).

Here are some examples of using the Python replace() method:

# Example 1: Replace all occurrences of 'lemons' with 'oranges'
mystr = 'lemons, bananas, lemons, apples, cherries'
newstr = mystr.replace('lemons', 'oranges')
print(newstr)

# Output: oranges, bananas, oranges, apples, cherries

# Example 2: Replace only one occurrence of 'apples' with 'pears'
mystr = 'lemons, bananas, lemons, apples, cherries'
newstr = mystr.replace('apples', 'pears', 1)
print(newstr)

# Output: lemons, bananas, lemons, pears cherries

# Example 3: Replace numbers or symbols

mystr = '#100'
newstr = mystr.replace('#','$')
print(newstr)

# Output: $100

If you have any questions about this code, you can drop a line in comment.

Comments

Popular posts from this blog

Python chr() Built in Function

Stock Market Predictions with LSTM in Python

Collections In Python

Python Count Occurrence Of Elements

Python One Liner Functions