Python has numerous string modifying methods, and one of them is the
In this article, I'll show you how this method can be used to replace a character in a string.
replace Method Works in Python
replace string method returns a new string with some characters from the original string replaced with new ones. The original string is not affected or modified.
The syntax of the
replace method is:
string.replace(old_char, new_char, count)
old_char argument is the set of characters to be replaced.
new_char argument is the set of characters that replaces the
count argument, which is optional, specifies how many occurrences will be replaced. If this is not specified, all occurrences of the
old_char will be replaced with the
Let's see some examples.
You can see how the
count argument like this:
By applying a
When to Use the
replace Method in Python
A good use case of this method is to replace characters in a user's input to fit some standard.
Let's say, for example, you want users to enter their usernames but you don't want the whitespace character in the username input. You can use the
replace method to replace the whitespaces in the submitted strings with a hyphen. Here's how to do that:
user_input = "python my favorite" updated_username = user_input.replace(" ", "-") print(updated_username) # python-my-favorite
From the result of the
replace method, you can see that the whitespaces have been replaced with hyphens which meets your standard.
replace method replaces an existing substring in a string with a new substring. You specify how many occurrences of the existing substring are to be replaced with the
count argument of the method.