Replace Method Of Str Class

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:

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:

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:

quote       = "begin at the beginning"

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

 

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

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

 

Output:

Original Quote:begin at the beginning

New Quote:Start at the beginning


Copyright 2019 © pythontic.com