In this article we will discuss how to replace single or multiple characters in a string in Python.

Python provides a str.replace() function i.e.

str.replace(old, new , count)

It returns a new string object that is a copy of existing string with replaced content. Also,

  • If count is not provides then it will return a string with all the occurrences of ‘old’, replaced with ‘new’ string.
  • If count parameter is passed then it will return a string with first ‘count’ occurrences of ‘old’ string replaced with ‘new’ string.

Let’s understand by examples,

Replace all occurrences of given character / string in a string

Suppose we have a string i.e.

mainStr = "Hello, This is a sample string"

Now, lets replace all the occurrences of ‘s’ with ‘X’ i.e.
'''
Replace all occurrences of given character or string in main string
'''
otherStr = mainStr.replace('s' , 'X') 

Contents of otherStr is as follows,
Hello, ThiX iX a Xample Xtring

As strings are immutable in Python, so we can not change its content. Therefore member functions like replace() returns a new string.
As we have not provided the count parameter in replace() function. So, it will replace all the occurrences of ‘s’ with ‘X’.┬áBut what if we want to replace only first few occurrences instead of all? Let’s see how to do that,

Replace first n occurrences of given character / sub string in a string

Suppose we have a string i.e.

mainStr = "Hello, This is a sample string"

Now, lets replace first 2 occurrences of ‘s’ with ‘XXXS’ i.e.
'''
Replace First 2 occurrences of given character or string in main string
'''
otherStr = mainStr.replace('s' , 'XXXS', 2) 

Contents of otherStr is as follows,
Hello, ThiXXXS iXXXS a sample string

As we have passed the count parameter as 2, so only first 2 occurrences of ‘s’ will be replaced in the returned copy.

Replace multiple characters/strings in a string

str.replace() function can replace the occurrences of one given sub string only. But what if we want to replace multiple sub strings in a given string ?

Suppose we have a string i.e.

mainStr = "Hello, This is a sample string"

Now, how to replace all the occurrences of these three characters ‘s’, ‘l’, ‘a’ with this string ‘AA’ ?
Let’s create a new function over replace() to do that i.e.
'''
Replace a set of multiple sub strings with a new string in main string.
'''
def replaceMultiple(mainString, toBeReplaces, newString):
    # Iterate over the strings to be replaced
    for elem in toBeReplaces :
        # Check if string is in the main string
        if elem in mainString :
            # Replace the string
            mainString = mainString.replace(elem, newString)
    
    return  mainString

It will replace all the occurrences of strings in List toBeReplaces with newString in the main given list mainString.
Let’s see how to replace the occurrences of [‘s’, ‘l’, ‘a’] with “AA” i.e.
'''
Replace multiple characters / strings from a string
'''
# Replace all the occurrences of string in list by AA in the main list 
otherStr = replaceMultiple(mainStr, ['s', 'l', 'a'] , "AA")

Contents of otherStr is as follows,
HeAAAAo, ThiAA iAA AA AAAAmpAAe AAtring

Complete example is as follows,
'''
Replace a set of multiple sub strings with a new string in main string.
'''
def replaceMultiple(mainString, toBeReplaces, newString):
    # Iterate over the strings to be replaced
    for elem in toBeReplaces :
        # Check if string is in the main string
        if elem in mainString :
            # Replace the string
            mainString = mainString.replace(elem, newString)
    
    return  mainString     

def main():
    
    mainStr = "Hello, This is a sample string"

    '''
    Replace all occurrences of given character or string in main string
    '''
    otherStr = mainStr.replace('s' , 'X') 
     
    print("String with replaced Content : " , otherStr) 
    
    '''
    Replace First 2 occurrences of given character or string in main string
    '''
    otherStr = mainStr.replace('s' , 'XXXS', 2) 
     
    print(otherStr) 
    
    
    '''
    Replace multiple characters / strings from a string
    '''
    # Replace all the occurrences of string in list by AA in the main list 
    otherStr = replaceMultiple(mainStr, ['s', 'l', 'a'] , "AA")
    
    print(otherStr)
           
if __name__ == '__main__':
    main()


Output:
String with replaced Content :  Hello, ThiX iX a Xample Xtring
Hello, ThiXXXS iXXXS a sample string
HeAAAAo, ThiAA iAA AA AAAAmpAAe AAtring