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:

string.replace(old, new, count)
  • 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 the old substring will be replaced.

Example 1: Basic usage

# Example 1: Replacing a substring my_string = "Hello, world! Hello, everyone!" new_string = my_string.replace("Hello", "Hi") print(new_string) # Output: "Hi, world! Hi, everyone!"

In this example:

  • The substring "Hello" is replaced with "Hi" in the original string.
  • Both occurrences of "Hello" are replaced because count is not specified.

Example 2: Specifying the count

# Example 2: Specifying the maximum number of replacements my_string = "apple banana apple orange apple" new_string = my_string.replace("apple", "kiwi", 2) print(new_string) # Output: "kiwi banana kiwi orange apple"

Here:

  • Only the first two occurrences of "apple" are replaced with "kiwi".
  • The third occurrence remains unchanged.

Example 3: Replacing with an empty string

# Example 3: Removing a substring my_string = "Hello, world!" new_string = my_string.replace("world", "") print(new_string) # Output: "Hello, !"

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 as old, the string remains the same, unless count is specified and there are occurrences of old.

Example 4: Case sensitivity

# Example 4: Case sensitivity my_string = "Hello, world! hello, everyone!" new_string = my_string.replace("hello", "hi") print(new_string) # Output: "Hello, world! hi, everyone!"

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

# Example 5: Non-existent substring my_string = "Hello, world!" new_string = my_string.replace("foo", "bar") print(new_string) # Output: "Hello, world!"

Here:

  • Since "foo" is not found in the original string, the output remains the same.