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

Python String replace() Method

Last Updated : 28 Oct, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

The replace() method replaces all occurrences of a specified substring in a string and returns a new string without modifying the original string.

Let’s look at a simple example of replace() method.

Python
s = "Hello World! Hello Python!"

# Replace "Hello" with "Hi"
s1 = s.replace("Hello", "Hi")

print(s1)

Output
Hi World! Hi Python!

Explanation: Here, “Hello” is replaced by “Hi” throughout the string, resulting in “Hi World! Hi Python!“.

Note: Since replace() creates a new string, the original string remains unchanged.

Syntax of String replace() Method

string.replace(old, new, count)

Parameters

  • old: The substring we want to replace.
  • new: The new substring that we want to replace with old substring.
  • count (optional): Specifies the maximum number of replacements to perform. If omitted, all occurrences are replaced.

Return Type

  • Returns a new string with the specified replacements made. The original string remains unchanged since strings in Python are immutable.

Using replace() with Count Limit

By using the optional count parameter, we can limit the number of replacements made. This can be helpful when only a specific number of replacements are desired.

Python
s = "apple apple apple"

# Replace "apple" with "orange" only once
s1 = s.replace("apple", "orange", 1)

print(s1)

Output
orange apple apple

Explanation: replace() method only replaces the first instance of “apple” because we specified count=1.

Case Sensitivity in replace()

The replace() method is case-sensitive, it treats uppercase and lowercase characters as distinct. If we want to replace both cases then we have to use additional logic.

Python
s = "Hello, World! hello, world!"

# Replace only lowercase 'hello'
s1 = s.replace("hello", "hi")
print(s1)

# Replace only uppercase 'Hello'
s2 = s.replace("Hello", "Hi")
print(s2)

Output
Hello, World! hi, world!
Hi, World! hello, world!



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 & 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
Numpy string operations | replace() function
In the numpy.core.defchararray.replace() function, each element in arr, return a copy of the string with all occurrences of substring old replaced by new. Syntax : numpy.core.defchararray.replace(arr, old, new, count = None) Parameters : arr : [array-like of str] Given array-like of string. old : [str or unicode] Old substring you want to replace.
1 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
MongoDB Python - Insert and Replace Operations
This article focus on how to replace document or entry inside a collection. We can only replace the data already inserted in the database. Prerequisites : MongoDB Python Basics Method used: replace_one() Aim: Replace entire data of old document with a new document Insertion In MongoDB We would first insert data in MongoDB. C/C++ Code # Python code
3 min read
Map function and Lambda expression in Python to replace characters
Given a string S, c1 and c2. Replace character c1 with c2 and c2 with c1. Examples: Input : str = 'grrksfoegrrks' c1 = e, c2 = r Output : geeksforgeeks Input : str = 'ratul' c1 = t, c2 = h Output : rahul We have an existing solution for this problem in C++. Please refer to Replace a character c1 with c2 and c2 with c1 in a string S. We can solve th
2 min read
Python | Pandas Series.replace()
Pandas series is a One-dimensional ndarray with axis labels. The labels need not be unique but must be a hashable type. The object supports both integer- and label-based indexing and provides a host of methods for performing operations involving the index. Pandas Series.replace() function is used to replace values given in to_replace with value. Th
3 min read
Python | Replace negative value with zero in numpy array
Given numpy array, the task is to replace negative value with zero in numpy array. Let’s see a few examples of this problem. Method #1: Naive Method C/C++ Code # Python code to demonstrate # to replace negative value with 0 import numpy as np ini_array1 = np.array([1, 2, -3, 4, -5, -6]) # printing initial arrays print("initial array&qu
4 min read
Python | Replace sublist with other in list
Sometimes, while working with Python, we can have a problem in which we need to manipulate a list in such a way that we need to replace a sublist with another. This kind of problem is common in the web development domain. Let's discuss certain ways in which this task can be performed. Method #1 : Using loop ( When sublist is given ) This method is
10 min read
Replace the column contains the values 'yes' and 'no' with True and False In Python-Pandas
Let’s discuss a program To change the values from a column that contains the values 'YES' and 'NO' with TRUE and FALSE. First, Let's see a dataset. Code: C/C++ Code # import pandas library import pandas as pd # load csv file df = pd.read_csv("supermarkets.csv") # show the dataframe df Output : For downloading the used csv file Click Here.
2 min read
Python - tensorflow.DeviceSpec.replace()
TensorFlow is open-source Python library designed by Google to develop Machine Learning models and deep learning neural networks. replace() is used to override the specification of DeviceSpec object and get the new object. Syntax: tensorflow.DeviceSpec.replace(**kwargs) Parameters: **kwargs: This method accepts all the parameters accepted by Device
1 min read
How to replace a word in excel using Python?
Excel is a very useful tool where we can have the data in the format of rows and columns. We can say that before the database comes into existence, excel played an important role in the storage of data. Nowadays using Excel input, many batch processing is getting done. There may be the requirement of replacing text in Excel sheet is always there as
3 min read
Python - Find text using beautifulSoup then replace in original soup variable
Python provides a library called BeautifulSoup to easily allow web scraping. BeautifulSoup object is provided by Beautiful Soup which is a web scraping framework for Python. Web scraping is the process of extracting data from the website using automated tools to make the process faster. The BeautifulSoup object represents the parsed document as a w
3 min read
Replace infinity with large finite numbers and fill NaN for complex input values using NumPy in Python
In this article, we will cover how to fill Nan for complex input values and infinity values with large finite numbers in Python using NumPy. Example: Input: [complex(np.nan,np.inf)] Output: [1000.+1.79769313e+308j] Explanation: Replace Nan with complex values and infinity values with large finite. numpy.nan_to_num method The numpy.nan_to_num method
3 min read
Datetime.replace() Function in Python
Datetime.replace() function is used to replace the contents of the DateTime object with the given parameters. Syntax: Datetime_object.replace(year,month,day,hour,minute,second,microsecond,tzinfo) Parameters: year: New year value in range-[1,9999],month: New month value in range-[1,12],day: New day value in range-[1,31],hour: New hour value in range
2 min read
replace() Function Of Datetime.date Class In Python
replace() function is used to manipulate the object of DateTime class of module of DateTime. Generally, it replaces the date( Year, Month, Day) and returns a new DateTime object. Syntax: replace(year=self.year, month=self.month, day=self.day) Parameters: Year: New year value (range: 1 <= year <= 9999)month: New month value(range: 1 <= mont
2 min read
How to search and replace text in a file in Python ?
In this article, we will learn how we can replace text in a file using python. Method 1: Searching and replacing text without using any external module Let see how we can search and replace text in a text file. First, we create a text file in which we want to search and replace text. Let this file be SampleFile.txt with the following contents: To r
5 min read
Python NumPy - Replace NaN with zero and fill positive infinity for complex input values
In this article, we will see how to replace NaN with zero and fill positive infinity for complex input values in Python. Numpy package provides us with the numpy.nan_to_num() method to replace NaN with zero and fill positive infinity for complex input values in Python. This method substitutes a nan value with a number and replaces positive infinity
4 min read
Replace NaN with zero and fill negative infinity values in Python
In this article, we will cover how to replace NaN with zero and fill negative infinity values in Python using NumPy. Example Input: [ nan -inf 5.] Output: [0.00000e+00 9.99999e+05 5.00000e+00] Explanation: Replacing NaN with 0 and negative inf with any value. numpy.nan_to_num method The numpy.nan_to_num method is used to replace Nan values with zer
3 min read
Python | Pandas Timestamp.replace
Python is a great language for doing 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 Timestamp.replace() function is used to replace the member values of the given Timestamp. The function implements datetime.repla
3 min read
Copy And Replace Files in Python
In Python, copying and replacing files is a common task facilitated by modules like `shutil` and `os`. This process involves copying a source file to a destination location while potentially replacing any existing file with the same name. Leveraging functions like `shutil.copy2` and `os.remove`, this operation is crucial for updating or maintaining
2 min read
Replace Commas with New Lines in a Text File Using Python
Replacing a comma with a new line in a text file consists of traversing through the file's content and substituting each comma with a newline character. In this article, we will explore three different approaches to replacing a comma with a new line in a text file. Replace Comma With a New Line in a Text FileBelow are the possible approaches to rep
2 min read
Replace Green Screen using OpenCV- Python
Prerequisites: OpenCV Python TutorialOpenCV (Open Source Computer Vision) is a computer vision library that contains various functions to perform operations on pictures or videos. This library is cross-platform that is it is available on multiple programming languages such as Python, C++, etc.Green Screen removal is used in the VFX industry for cha
2 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg