The Wayback Machine - https://web.archive.org/web/20240720152547/https://www.geeksforgeeks.org/python-string-replace/
Open In App

Python String replace() Method

Last Updated : 05 Jul, 2024
Improve
Suggest changes
Post a comment
Like Article
Like
Save
Share
Report

The string replace() method returns a copy of the string where occurrences of a substring are replaced with another substring.

Example:

Python
string = "Hello World"
new_string = string.replace("Hello", "Good Bye")

print(new_string)

Output
Good Bye World

What is String replace() Method?

String replace() is a built-in function in Python and it is used to replace a substring with another string. It will replace every occurrence of that substring, so it should be used with caution.

It does not change the original string but returns a new one. It is mostly used in string substitution.

String replace() Method Syntax

string.replace(old, new, count)

Parameters:

  • old – old substring you want to replace.
  • new – new substring which would replace the old substring.
  • count – ( Optional ) the number of times you want to replace the old substring with the new substring.

Return Value :

It returns a copy of the string where all occurrences of a substring are replaced with another substring.

Python’s replace() method and more in-built function are valuable skill for anyone involved in text manipulation and data preprocessing tasks. To deepen your understanding of string operations and explore advanced techniques in data handling, check out our Complete Machine Learning & Data Science Program . This course covers everything from basic string manipulation to advanced data processing methods, empowering you to become proficient in Python programming and data analysis.

How to Use String replace() Function

You can easily use the replace() function, you just need to call the function with a string object and pass the strings as a parameter. The first parameter is the substring you want to replace, and the second parameter is the string you want to replace with.

Let’s understand it better how to replace a string in Python with a simple example:

Python
string = "Replace"
new_string = string.replace("Replace", "Replaced")

print(new_string)

Output
Replaced

More Examples of String replace() Method

In this section, we will see different examples of Python string replacement.

Example:

Python
string = "Good Morning"
new_string = string.replace("Good", "Great")

print(new_string)

Output
Great Morning

1. Replace all Instances of a Single Character in a String

In this example, we are only replacing a single character from a given string. The Python string replacement approach using the replace() method is case-sensitive, and therefore it performs a case-sensitive substring substitution, i.e. R in FOR is unchanged.

Example:

Python
string = "grrks FOR grrks"

# replace all instances of 'r' (old) with 'e' (new)
new_string = string.replace("r", "e" )

print(string)
print(new_string)

Output
grrks FOR grrks
geeks FOR geeks

Time Complexity: O(n)
Space Complexity: O(n)

2. Replace all Instances of a String in a String

Here, we will use the Python string replacement approach using replace() to replace all the geeks with GeeksforGeeks using the replace() function.

Example:

Python
string = "geeks for geeks \ngeeks for geeks"

print(string)

# Prints the string by replacing only
# 3 occurrence of Geeks
print(string.replace("geeks", "GeeksforGeeks"))

Output
geeks for geeks 
geeks for geeks
GeeksforGeeks for GeeksforGeeks 
GeeksforGeeks for GeeksforGeeks

Time Complexity: O(m*n)
Space Complexity: O(n)

3. Replace only a Certain Number of Instances in a String

In this example, we will use the Python string replacement approach using replace() replacing certain numbers of words. i.e. “ek” with “a” with count=3 .

Python
string = "geeks for geeks geeks geeks geeks"

# Prints the string by replacing 'e' by 'a'
print(string.replace("e", "a"))

# Prints the string by replacing only 3 occurrence of 'ek' by 'a'
print(string.replace("ek", "a", 3))

Output
gaaks for gaaks gaaks gaaks gaaks
geas for geas geas geeks geeks

Time Complexity: O(n)
Space Complexity: O(n)

4. Replace String using a List Comprehension and join() Method

Here, we will do string replacement without using replace(). First, we will split the original string into a list of substrings using the split() method . Then use a list comprehension to replace each occurrence of old_substring with new_substring.

Join the list of substrings back into a string using the join() method.

Python
my_string = "geeks for geeks "
old_substring = "k"
new_substring = "x"

split_list = my_string.split(old_substring)
new_list = [new_substring if i < len(split_list)-1 else '' for i in range(len(split_list)-1)]
new_string = ''.join([split_list[i] + new_list[i] for i in range(len(split_list)-1)] + [split_list[-1]])

print(new_string)

Output
geexs for geexs 

Time Complexity: O(n)
Space Complexity: O(n)

We have covered the definition, syntax, and examples of the string replace() method in Python. We also saw a technique to replace string without using the replace() function.

String replacement is a very important operation on strings. It is very easy and simple to use.

Read Other String Methods

Similar Reads:

Python String replace() Method – FAQs

What is replace() in Python?

replace() is a built-in string method in Python used to create a new string by replacing occurrences of a substring with another substring.

How to replace a string expression in Python?

You can use the replace() method to replace a substring with another substring in a string.

original_string = "Hello, world!"
new_string = original_string.replace("world", "Python")
print(new_string) # Output: Hello, Python!

How to change a string in Python?

In Python, strings are immutable , meaning you cannot change them in place. Instead, you create a new string with the desired changes using methods like replace().

original_string = "Hello, world!"
new_string = original_string.replace("world", "Python")
print(new_string) # Output: Hello, Python!

Can strings in Python be replaced?

Yes, strings in Python can be replaced using methods like replace() to create new strings with desired modifications.

How to replace characters in a string?

To replace characters in a string, use the replace() method with the characters you want to replace and their replacements.

original_string = "apple"
new_string = original_string.replace("a", "b")
print(new_string) # Output: bpple


Previous Article
Next Article

Similar Reads

replace() in Python to replace a substring
Given a string str that may contain one more occurrences of “AB”. Replace all occurrences of “AB” with “C” in str. Examples: Input : str = "helloABworld" Output : str = "helloCworld" Input : str = "fghABsdfABysu" Output : str = "fghCsdfCysu" This problem has existing solution please refer Replace all occurrences of string AB with C without using ex
1 min read
Python | Pandas Series.str.replace() to replace text in a series
Python is a great language for data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages that makes importing and analyzing data much easier. Pandas Series.str.replace() method works like Python .replace() method only, but it works on Series too. Before calling .replace() on a Panda
5 min read
Python String Methods | Set 3 (strip, lstrip, rstrip, min, max, maketrans, translate, replace &amp; expandtabs())
Some of the string methods are covered in the below sets.String Methods Part- 1 String Methods Part- 2More methods are discussed in this article1. strip():- This method is used to delete all the leading and trailing characters mentioned in its argument.2. lstrip():- This method is used to delete all the leading characters mentioned in its argument.
4 min read
Python - Replace all occurrences of a substring in a string
Sometimes, while working with Python strings, we can have a problem in which we need to replace all occurrences of a substring with other. Input : test_str = "geeksforgeeks" s1 = "geeks" s2 = "abcd" Output : test_str = "abcdforabcd" Explanation : We replace all occurrences of s1 with s2 in test_str. Input : test_str = "geeksforgeeks" s1 = "for" s2
3 min read
Python | sympy.replace() method
With the help of sympy.replace() method, we can replace the functions in the mathematical expression without editing the whole expression by using sympy.replace() method. Syntax : sympy.replace() Return : Return the replaced values in the mathematical expression. Example #1 : In this example we can see that by using sympy.replace() method, we are a
1 min read
Python - os.replace() method
Prerequisite: OS module in Python. os.replace() method in Python is used to rename the file or directory. If destination is a directory, OSError will be raised. If the destination exists and is a file, it will be replaced without error if the action performing user has permission. This method may fail if the source and destination are on different
2 min read
Python DateTime - time.replace() Method with Example
In this article, we will discuss the time.replace() method in Python. This method is used to manipulate objects of time class of module datetime. It is used to replace the time with the same value, except for those parameters given new values by whichever keyword arguments. Syntax: replace(year=self.year, month=self.month, day=self.day) Parameters:
2 min read
Replace missing white spaces in a string with the least frequent character using Pandas
Let's create a program in python which will replace the white spaces in a string with the character that occurs in the string very least using the Pandas library. Example 1: String S = "akash loves gfg" here: 'g' comes: 2 times 's' comes: 2 times 'a' comes: 2 times 'h' comes: 1 time 'o' comes: 1 time 'k' comes: 1 time 'v' comes: 1 time 'e' comes: 1
2 min read
Change the tag's contents and replace with the given string using BeautifulSoup
Prerequisites: Beautifulsoup Beautifulsoup is a Python library used for web scraping. This powerful python tool can also be used to modify html webpages. This article depicts how beautifulsoup can be employed to change contents within a tag and replace the contents to be changed with the given string. For this, replace_with() function of the module
1 min read
Replace NaN with Blank or Empty String in Pandas?
In this article, we will discuss how to replace NaN with Blank or Empty string in Pandas. Example: Input: "name": ['suraj', 'NaN', 'harsha', 'NaN'] Output: "name": ['sravan', , 'harsha', ' '] Explanation: Here, we replaced NaN with empty string.Replace NaN with Empty String using replace() We can replace the NaN with an empty string using df.replac
2 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg