Python

Python Menu

Python

Python String replace() - Definition, Syntax, Parameters, Examples

Definition

The replace() method replaces a specified phrase with another specified phrase. Note that all occurrences of the specified phrase will be replaced, if nothing is specified.

Syntax

string.replace(oldvalue, newvalue, count)

Parameters

Parameter Description
oldvalue Required. The string to search for
newvalue Required. The string to replace the old value with
count Optional. A number specifying how many occurrences of the old value you want to replace. Default is all occurrences

Examples:

testStr = "Welcome to the PHP tutorials." result = testStr.replace("PHP", "Python") print(result) # replacing all occurrence testStr = "Welcome to the PHP tutorials. PHP is a scripting language." result = testStr.replace("PHP", "Python") print(result) # replacing only the first 2 occurrence testStr = "Welcome to the PHP tutorials. PHP is a PHP scripting language." result = testStr.replace("PHP", "Python", 2) print(result)

Introduction

Python Basics

Python Advance

Data Science Python Tutorials

Python Functions and Methods