Replace a Character in a String

Python: Replace a Character in a String

A string is a character sequence.

A character is nothing more than a symbol. The English language, for example, has 26 characters.

Computers do not work with characters ,instead, they work with numbers (binary). Even though you see characters on your screen, they are stored and manipulated internally as a series of 0s and 1s.

The process of converting a character to a number is known as encoding, and the reverse process is known as decoding. Some of the most common encodings are ASCII and Unicode.

In Python, a string is a sequence of Unicode characters.. Unicode was created in order to include every character in all languages and bring encoding uniformity. Python Unicode can teach you about Unicode.

This article will go over various methods to replace a character in a string

Examples:

Input:

string="BTechGeeks" oldstring='e' replacestring='p'

Output:

BTpchGppks

Modifying a Character in a String

There are several ways to replace a character in a string some of them are:

Method #1: Using replace() to replace all occurences

The Python string method replace() returns a copy of the string with old occurrences replaced with new, with the number of replacements optionally limited to max.

Syntax :

string .replace(old, new, count)

Parameters:

  • old−This is an old substring that needs to be replaced.
  • new − This is a new substring that will replace the old one.
  • max − Only the first count occurrences are replaced if the optional argument max is provided.

Return:
This method returns a string copy in which all occurrences of substring old are replaced with new. Only the first count occurrences are replaced if the optional argument max is provided.

Below is the implementation:

# Function which replaces the string
def replaceString(string, oldstring, replacestring):
    # Replace all occurrences of a character in string in python
    resultstring = string.replace(oldstring, replacestring)

    # return the final string
    return resultstring

# Driver code
# given string
string = "BTechGeeks"
# string which needs to be replaced
oldstring = 'e'
# replacing string/new string
replacestring = 'p'
# passing these strings to replaceString function
print(replaceString(string, oldstring, replacestring))

Output:

BTpchGppks

In this case, we passed the character to be replaced ‘e’ as the first argument and the character ‘p’ as the second. The replace() method then returned a copy of the original string by replacing all occurrences of the character’s’ with the character ‘X’.

Because strings are immutable in Python, we cannot change their contents. As a result, the replace() function returns a copy of the string containing the replaced content.

Replace only first two occurences of string:

Instead of replacing all occurrences of a character in a string, we can use the count argument in the replace() function to replace only the first few occurrences of a character in a string.

Below is the implementation:

# Function which replaces the string
def replaceString(string, oldstring, replacestring):
    # Replace first 2 occurrences of a character in string in python
    resultstring = string.replace(oldstring, replacestring, 2)

    # return the final string
    return resultstring


# Driver code
# given string
string = "BTechGeeks"
# string which needs to be replaced
oldstring = 'e'
# replacing string/new string
replacestring = 'p'
# passing these strings to replaceString function
print(replaceString(string, oldstring, replacestring))

Output:

BTpchGpeks

In this case, we passed the character to be replaced ‘e’ as the first argument and the character ‘p’ as the second. The third argument was then passed as 2. The third argument is optional and tells the replace() function how many occurrences of the given sub-string should be replaced.

The replace() method then returned a copy of the original string by replacing only the first two occurrences of ‘e’ with the symbol ‘p.’
Because strings are immutable in Python, we cannot change their contents. As a result, the replace() function returns a duplicate of the string with the replaced content.

Method #2:Using for loop

Create an empty string and then iterate through all of the characters in the original string. Add each character to the new string during iteration. However, if a character needs to be replaced, use the replacement character instead.

Below is the implementation:

# Function which replaces the string
def replaceString(string, oldstring, replacestring):
  # taking a empty string
    resultstring = ''
    # Traversee the originalstring
    for element in string:
      # if character is equal to old string then replace it
        if(element == oldstring):
            resultstring += replacestring
        else:
            resultstring += element

    # return the final string
    return resultstring


# Driver code
# given string
string = "BTechGeeks"
# string which needs to be replaced
oldstring = 'e'
# replacing string/new string
replacestring = 'p'
# passing these strings to replaceString function
print(replaceString(string, oldstring, replacestring))

Output:

BTpchGppks

It replaced all instances of the character ‘e’ with the letter ‘p’

Because strings are immutable in Python, we cannot change their contents. As a result, we made a new copy of the string that contained the replaced content.

Method #3:Using Regex

Python includes a regex module (re), which includes a function sub() for replacing the contents of a string based on patterns. We can use the re.sub() function to replace/substitute all occurrences of a character in a string.

Below is the implementation:

import re

# Function which replaces the string
def replaceString(string, oldstring, replacestring):
    # using regex
    resultstring = re.sub(oldstring, replacestring, string)

    # return the final string
    return resultstring


# Driver code
# given string
string = "BTechGeeks"
# string which needs to be replaced
oldstring = 'e'
# replacing string/new string
replacestring = 'p'
# passing these strings to replaceString function
print(replaceString(string, oldstring, replacestring))

Output:

BTpchGppks

In this case, we used the sub() function with the character to be replaced ‘e’ as the first argument and the character ‘p’ as the second argument. The third argument was then passed as the original string.

The Sub() function treated the first argument ‘s’ as a pattern and replaced all matches with the given replacement string, i.e ‘p’. As a result, it replaced all instances of the character ‘e’ with the character ‘p’ .Because strings are immutable in Python, we cannot change their contents. As a result, the regex module’s sub() function returns a copy of the string with the replaced content.
Related Programs: