How to Use String replace() Method in PythonPython Basics


The replace() method returns a copy of the string where all occurrences of a substring are replaced with another substring.

Example

#!/usr/bin/python3
# -*- coding: UTF-8 -*-

str = "nice to meet you, have a nice day!"
print( str)
print( str.replace("nice", "good"))

Output:

nice to meet you, have a nice day!
good to meet you, have a good day!

Syntax

str.replace(old, new [, count])

Parameters

Name Description
old Old substring you want to replace
new New substring which would replace the old substring

Return Value

It returns a copy of the string where the old substring is replaced with the new substring.

© 2024 Cheerlearn.com, all rights reserved. Privacy Policy | Contact Us