In this article, we will discuss different ways to replace a character in string in python.
Overview:
- Replace all occurrences of a character in string using replace()
- Replace the first two occurrences of a character in string
- Replace a character in a string using regex
- Replace a character in a string using for loop
Replace all occurrences of a character in string in python using replace()
In python, the String class (Str) provides a method replace() to replace the sub-strings in a string. We can use that to replace all the occurrences of a character in a string with another character. For example,
org_string = "This is a sample string" # Replace all occurrences of a character in string in python new_string = org_string.replace('s', 'X') print(new_string)
Output:
ThiX iX a Xample Xtring
Here we passed the character to be replaced ‘s’ as the first argument and character ‘X’ as the second argument. Then replace() method returned a copy of the original string by replacing all the occurrences of character ‘s’ with the ‘X’.
As strings are immutable in Python, i.e., we cannot change its contents. Therefore replace() function returns a copy of the string with the replaced content.
Know more about Str.replace() method and check out more examples.
Replace the first two occurrences of a character in string in python
Instead of replacing all occurrences of a character in a string, we can replace only the first few occurrences of a character in a string by passing the count argument in the replace() function i.e.
org_string = "This is a sample string" # Replace first two occurrences of a character in string new_string = org_string.replace('s', 'X', 2) print(new_string)
Output:
ThiX iX a sample string
Here we passed the character to be replaced ‘s’ as the first argument and character ‘X’ as the second argument. Then we passed the third argument as 2. The third argument is optional and it tells the replace() function that how many occurrences of given sub-string need to be replaced.
Then replace() method returned a copy of the original string by replacing only first two occurrences of ‘s’ with the ‘X’.
As strings are immutable in Python, i.e., we cannot change its contents. Therefore replace() function returns a copy of the string with the replaced content.
Replace a character in a string using regex in python
Python provides a regex module (re), and in this module, it provides a function sub() to replace the contents of a string based on patterns. We can use this re.sub() function to substitute/replace all occurrences of a character in the string,
import re # Replace a character in string using regex in python new_string = re.sub('s', 'X', org_string) print(new_string)
Output:
ThiX iX a Xample Xtring
Here we passed the character to be replaced ‘s’ as the first argument and character ‘X’ as the second argument in the sub() function. Then we passed the third argument as the original string.
Sub() function used the first argument as a pattern and replaced all the matches of that pattern with the given replacement string, i.e., ‘X’. So, it replaced all the occurrences of character ‘s’ with the character ‘X’. As strings are immutable in python i.e., we cannot change its contents. Therefore sub() function of the regex module returns a copy of the string with the replaced content.
Replace a character in a string using for loop in python
Initialize an empty string and then iterate over all characters of the original string. During iteration, add each character to the new string. But for the characters that needs replacement, use the replacement character instead. For example,
to_replace = 's' replaced = 'X' # Replace a character in string using for loop new_string = '' for elem in org_string: if elem == to_replace: new_string += replaced else: new_string += elem print(new_string)
Output:
ThiX iX a Xample Xtring
It replaced all the occurrences of character ‘s’ with the ‘X’.
As strings are immutable in Python, i.e., we cannot change its contents. Therefore, we created a new copy of the string with the replaced content.
Summary
We can replace a character in a string with another character in python by using the replace() function or sub() function or a for loop.
Pandas Tutorials -Learn Data Analysis with Python
-
Pandas Tutorial Part #1 - Introduction to Data Analysis with Python
-
Pandas Tutorial Part #2 - Basics of Pandas Series
-
Pandas Tutorial Part #3 - Get & Set Series values
-
Pandas Tutorial Part #4 - Attributes & methods of Pandas Series
-
Pandas Tutorial Part #5 - Add or Remove Pandas Series elements
-
Pandas Tutorial Part #6 - Introduction to DataFrame
-
Pandas Tutorial Part #7 - DataFrame.loc[] - Select Rows / Columns by Indexing
-
Pandas Tutorial Part #8 - DataFrame.iloc[] - Select Rows / Columns by Label Names
-
Pandas Tutorial Part #9 - Filter DataFrame Rows
-
Pandas Tutorial Part #10 - Add/Remove DataFrame Rows & Columns
-
Pandas Tutorial Part #11 - DataFrame attributes & methods
-
Pandas Tutorial Part #12 - Handling Missing Data or NaN values
-
Pandas Tutorial Part #13 - Iterate over Rows & Columns of DataFrame
-
Pandas Tutorial Part #14 - Sorting DataFrame by Rows or Columns
-
Pandas Tutorial Part #15 - Merging or Concatenating DataFrames
-
Pandas Tutorial Part #16 - DataFrame GroupBy explained with examples
Are you looking to make a career in Data Science with Python?
Data Science is the future, and the future is here now. Data Scientists are now the most sought-after professionals today. To become a good Data Scientist or to make a career switch in Data Science one must possess the right skill set. We have curated a list of Best Professional Certificate in Data Science with Python. These courses will teach you the programming tools for Data Science like Pandas, NumPy, Matplotlib, Seaborn and how to use these libraries to implement Machine learning models.
Checkout the Detailed Review of Best Professional Certificate in Data Science with Python.
Remember, Data Science requires a lot of patience, persistence, and practice. So, start learning today.