Python Replace Character in String

Python Replace Character In String | 6 Best Methods to Follow

Facing it challenging to replace character in string Python? If yes, then have a look at 6 methods on Python replace character in string.

Character replacement in strings is a very important task. It has many uses, such as cleaning data, formatting text, and garbage collection, without which, many of our modern apps and softwares wouldn’t be useful to us as they are now.

In this article, you’ll first learn the basics of strings in Python. Next, you’ll learn different ways to replace characters in Python strings.

What are Strings in Python? A string is basically a sequence of characters, regardless of the programming language. A letter is any symbol. Numbers, letters, operators, and special characters (#, @, ~, etc.) are all considered symbols in Python.

Since Python does not have a separate data type for characters (like C++ or Java), every character is treated as a string, even a single character. Because of this, strings in Python are immutable (you can’t change them after they’re created).

Modifications such as character substitutions, described later, are made on a copy of the original string, not on the original string itself.

Example

s1 = "this is a string"

print (e1)

Output

this is a string

What is a String in Python ?

Strings regardless of the programming language, are basically sequence of characters. A character is any symbol. Numbers, alphabets, operators, special characters(#, @, ~ etc.) are all considered as symbols in python.

See also  Know The Top 9 Main Uses of Python In The Real World.

Python does not have any separate data type for characters (like C++ or Java), so every character, even if it is a single character is considered as a string. Due to this reason, strings are immutable in python (they cannot be changed once created).

Any changes, like the character replacement which we will discuss later, are done on a copy of the original string and not on the original string itself.

Example

s1 = "This is a string"

print(s1)

Output

This is a string

How to Python Replace Character in String?

There are many ways for Python replace character in string. We will discuss them separately.

Using Slicing Method

Slicing method is a way in python which gives you the string before or after a given index. It is used with the following syntax:

substring = str[start_index : end_index]

The example to use slicing for character replacement is given below.

Example

str = 'string'

index = 0

new_character = 'S'

str = str[:index] + new_character + str[index+1:]

print(str)

Output

String

Using Replace() Function

Python has many inbuilt function for efficient and easy programming experience. The string replace function is an inbuilt function to replace a character in a string.

The replace function takes the character(or group of consecutive characters) that need to be replaced and the replacement string, with which they will be replaced. It returns the new strings with the replaced character.

Example

str = 'string'

new_character = 'S'

str = str.replace('s', new_character)

print(str)

Output

String

Using List

This method takes advantage of the fact that lists are mutable. First, convert the given string to a list. Then replace the character with the list index. Then join the list and the empty string with the join function. This will return a string with the changes you want.

See also  Flutter VS Ionic: Know The Main Differences

Example

str = 'string'

lis = list(str)

index = 0

lis[index] = 'S'

str = "".join(lis)

print(str)

Output

String

You May Also Like

XOR in Python | Top 3 Applications of XOR Operator in Python

Replacing Multiple Characters with a Single Character

The approach here is to iterate over the string and using the slicing method(discussed above) for every occurrence of the characters we want to replace.

Example

str = 'string'

indexes = [2, 4, 5] 

new_character = 'a' 

result = '' 

for i in indexes:

    str = str[:i] + new_character + str[i+1:] 

print(str)

Output

staiaa

Replacing Multiple Characters with Multiple Characters

This method uses the above method, but with slight modification. Just like the above example, we will iterate over the string to find the characters in to be replaced and replace them with the respective characters. The below example uses dictionary data structure to implement this method.

Example

str = 'string'

indexes = {2: 'a',

           4: 'b',

           5: 'c'}

result = ''

# Replace multiple characters with different replacement characters

for index, replacement in indexes.items():

    str = str[:index] + indexes[index] + str[index + 1:]

print(str)

Output

staibc

Using Regex Module

The Regex module is a python module which contains functions specifically for string data handling. It contains functions for obtaining substring, replace string and many other tasks.

We can import the regex module and use the replace sub function. It takes 3 parameters : the string to be replaced, the new string, the original string and returns the modified string.

Example

import re

sentence = 'My name is Rahul'

new_sentence = re.sub('Rahul', 'Shantanu', sentence)

print(new_sentence)

Output

My name is Shantanu

Conclusion

We have discussed several methods of Python replace character in string. Character replacement is a very frequently done task in programming.

See also  How to Tackle Java Programming Projects

Therefore, it is necessary to learn every method as well as to understand which method is suitable for a given situation. This understanding will help in writing fast and efficient programs. If you think we have missed any of the method on Python replace character in string then comment down below.

Leave a Comment

Your email address will not be published. Required fields are marked *