python logo

python string replace


Python hosting: Host, run, and code Python in the cloud!

The Python str.replace() method allows users to replace specified substrings in a given string. By using this method, you can easily manipulate and modify strings to fit desired outputs.

Syntax of the str.replace() Method in Python

The typical format to use the replace method is as follows:

str.replace(old, new, max)

Detailed Description of Parameters

Below is a breakdown of the parameters you can use with the str.replace() method:

Parameter Description
old The substring you want to search for and replace.
new The substring that will replace the old substring.
max It specifies the maximum number of occurrences to replace. If not provided, it will replace all occurrences.

Practical Example of Using str.replace()

Consider the following Python code that demonstrates the use of the replace method:

s = "All work and no play makes Jack a dull boy. Jack?"
s = s.replace("Jack","Joe")
print(s)

When executed, the output will be:

All work and no play makes Joe a dull boy. Joe?

This shows how “Jack” was successfully replaced by “Joe” in the given string.

For more string manipulation methods, you can refer to the previous tutorial on string uppercase.






Leave a Reply: