Python str.replace() function
str.replace()
Function in Python
The str.replace()
function in Python is used to replace occurrences of a specified substring with another substring within a string. This function is useful for modifying strings by changing certain parts of them to new values.
Syntax:
old
: The substring you want to replace.new
: The substring you want to use as the replacement.count
(optional): An integer specifying the maximum number of occurrences to replace. If omitted, all occurrences of theold
substring will be replaced.
Example 1: Basic usage
In this example:
- The substring
"Hello"
is replaced with"Hi"
in the original string. - Both occurrences of
"Hello"
are replaced becausecount
is not specified.
Example 2: Specifying the count
Here:
- Only the first two occurrences of
"apple"
are replaced with"kiwi"
. - The third occurrence remains unchanged.
Example 3: Replacing with an empty string
In this case:
- The substring
"world"
is replaced with an empty string, effectively removing it from the original string.
Key Points:
str.replace()
creates and returns a new string with the specified substitutions; it does not modify the original string.- The function is case-sensitive, meaning
"Hello"
and"hello"
would be treated as different substrings. - If the
old
substring is not found, the original string remains unchanged. - If the
new
substring is the same asold
, the string remains the same, unlesscount
is specified and there are occurrences ofold
.
Example 4: Case sensitivity
In this example:
- Only the second occurrence of
"hello"
(with a lowercase "h") is replaced with"hi"
, while"Hello"
(with an uppercase "H") remains unchanged.
Example 5: Replacing non-existent substring
Here:
- Since
"foo"
is not found in the original string, the output remains the same.