str.replace()
Added in v3.x · Updated March 13, 2026 · String Methods
stdlib string methods
The .replace() method returns a copy of the string with all occurrences of a substring replaced by a new value. It is one of the most commonly used string methods in Python.
Signature
str.replace(old, new[, count])
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
old | str | Required | The substring to search for and replace |
new | str | Required | The replacement string |
count | int | -1 (all) | Maximum number of replacements. -1 means replace all. |
Return Value
Returns a new string with replacements made. The original string remains unchanged.
Basic Examples
Replace all occurrences
text = "Hello World"
result = text.replace("World", "Python")
print(result) # Output: Hello Python
Replace with empty string (remove substring)
text = "Remove all spaces"
result = text.replace(" ", "")
print(result) # Output: Removeallspaces
Limit replacements with count
text = "one one one one"
result = text.replace("one", "1", count=2)
print(result) # Output: 1 1 one one
Practical Use Cases
Cleaning user input
def clean_username(username):
# Remove leading/trailing whitespace and replace internal spaces with underscore
return username.strip().replace(" ", "_")
print(clean_username(" john doe ")) # Output: john_doe
Simple text templating
template = "Hello {name}, your order #{order} is ready"
message = template.replace("{name}", "Alice").replace("{order}", "12345")
print(message) # Output: Hello Alice, your order #12345 is ready
Sanitizing text
# Replace multiple consecutive newlines with a single one
text = "Line 1\n\n\n\nLine 2"
cleaned = text.replace("\n\n\n\n", "\n\n")
print(cleaned)
# Output:
# Line 1
#
# Line 2
Case-insensitive replacement
text = "Hello HELLO hello"
# For case-insensitive, convert to lower first
lower_text = text.lower()
result = lower_text.replace("hello", "Hi")
print(result) # Output: hi hi hi
Behavior Notes
.replace()does not use regular expressions. For pattern-based replacement, use theremodule withre.sub().- If
oldis not found, the original string is returned unchanged. - The method is case-sensitive.
- Empty
oldstring insertsnewat every position including start and end:
result = "abc".replace("", "X")
print(result) # Output: XaXbXcX