Wednesday, July 1, 2020

Python String replace() Method

Python String replace() method is used to replace occurrences of the specified substring with the new substring.

Syntax of replace() method

Syntax of replace() method is-

str.replace(old, new, count)

old- Specifies a substring that has to be replaced.

new- Specifies a substring that replaces the old substring.

count- count argument is optional if it is given, only the first count occurrences are replaced. If count is not specified then all the occurrences are replaced.

Return values of the method is a copy of the string with all occurrences of substring old replaced by new.

Replace() method Python examples

1. Replacing specified substring with new value.

def replace_sub(text):
    text = text.replace('30', 'thirty')
    print(text)

replace_sub('His age is 30')

Output

His age is thirty

2. replace() method with count parameter to replace only specified occurrences.

def replace_sub(text):
    text = text.replace('is', 'was')
    print(text)
    # replacing only one occurrence
    print(text.replace('was', 'is', 1))

replace_sub('His age is 30')

Output

Hwas age was 30
His age was 30

3. Replacing character with space.

def replace_sub(text):
    text = text.replace('H', '')
    print(text)

replace_sub('His age is 30')

Output

is age is 30

That's all for this topic Python String replace() Method. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Python Tutorial Page


Related Topics

  1. Removing Spaces From String in Python
  2. String Slicing in Python
  3. Python String isdigit() Method
  4. Python String isnumeric() Method
  5. Local, Nonlocal And Global Variables in Python

You may also like-

  1. Constructor in Python - __init__() function
  2. Installing Anaconda Distribution On Windows
  3. Python while Loop With Examples
  4. Multiple Inheritance in Python
  5. BigDecimal in Java
  6. Java Stream API Tutorial
  7. Difference Between Two Dates in Java
  8. Transaction Management in Spring