replace method of str class

The replace() method of str class in Python replaces the occurrences of a substring with another substring for a specified number of times.

Str Updated 13 Mar 2017 1 min read

Method Name

replace

Method Name

replace(oldSubString, newSubString[, count])

Method Overview

  • The replace method of python str class replaces occurrences of specified substring with another substring.

  • The number of times the replacement should happen can be specified.

Parameters

oldSubString - The substring that needs to be replaced

newSubString - The new substring that is replacing the old one

count - Number of times the old substring needs to be replaced

with the new substring

Return Value

The new string in which occurrences of the old substring is replaced with the new substring.

Example 1

python
testString  = "I felt happy because I saw the others were happy"

newString   = testString.replace("I", "He")

print("Original String:{}".format(testString))

print("New String:{}".format(newString))

text        = "was young the way an actual young person is young"

newText     = testString.replace("young", "smart")

print("==========")

print("Original Text:{}".format(text))

print("New Text:{}".format(newText))

Output

Output
Original String:I felt happy because I saw the others were happy

New String:He felt happy because He saw the others were happy

==========

Original Text:was young the way an actual young person is young

New Text:I felt happy because I saw the others were happy

Example 2

python
quote       = "begin at the beginning"

newQuote    = quote.replace("begin", "Start", 1)

print("Original Quote:{}".format(quote))

print("New Quote:{}".format(newQuote))

Output

Output
Original Quote:begin at the beginning

New Quote:Start at the beginning