When processing text data, operations like deleting specific characters or replacing them with other words are very common.
Python’s string type (str) provides the standard method replace() for this purpose. Using this method, you can easily perform everything from simple full replacements to partial replacements with a specified number of times.
This article explains the basic usage of the replace() method and how to limit the number of replacements.
Basic Syntax of the replace() Method
The replace() method searches for a “substring to find” within a string and returns a new string where it is replaced by a “new string”.
Syntax:
new_string = original_string.replace(character_to_replace, new_character)
Specific Usage Example: Deleting Unwanted Characters
Here is an example of removing hyphens (-) from phone number data to make it a string of numbers only.
# Phone number with hyphens
phone_number = "090-1234-5678"
# Replace hyphen "-" with empty string "" (delete)
clean_number = phone_number.replace("-", "")
print(f"Original string: {phone_number}")
print(f"String after replacement: {clean_number}")
Execution Result:
Original string: 090-1234-5678
String after replacement: 09012345678
By default, if there are multiple matching characters, all of them are replaced.
Specifying the Number of Replacements (count Argument)
If you pass an integer (count) as the third argument to the replace() method, you can perform replacements only a specified number of times starting from the beginning.
Syntax:
new_string = original_string.replace(character_to_replace, new_character, count)
Specific Usage Example: Fixing Only the Beginning
This is an example where you want to change only the first “Error” to “Warning” in a system log message, but leave the second and subsequent occurrences as they are.
# Log message containing multiple "Error"s
log_message = "[Error] Connection failed. Error code: 500"
# Replace only the first one with "Warning"
updated_log = log_message.replace("Error", "Warning", 1)
print(f"Before fix: {log_message}")
print(f"After fix: {updated_log}")
Execution Result:
Before fix: [Error] Connection failed. Error code: 500
After fix: [Warning] Connection failed. Error code: 500
You can confirm that the first [Error] changed to [Warning], but the Error code part later remained unchanged.
Important Note: The Original String is Not Changed (Non-destructive)
Python strings are “immutable” (cannot be changed). Therefore, executing the replace() method does not rewrite the content of the original variable.
To use the replacement result, you must assign it to a new variable or re-assign it to the original variable.
text = "apple, banana, cherry"
# This alone does not change text
text.replace("banana", "grape")
print(f"No assignment: {text}")
# You can keep the result by assigning to a variable
text = text.replace("banana", "grape")
print(f"With assignment: {text}")
Execution Result:
No assignment: apple, banana, cherry
With assignment: apple, grape, cherry
Summary
- str.replace(old, new): Replaces all occurrences of
oldwithnewin the string. - str.replace(old, new, count): Replaces only
counttimes from the beginning. - To delete strings, specify an empty string
""as the new character. - Since the original string is not changed, assign the result to a variable to use it.
