Python

Python Replace Characters in a String

In Python, “string” characters are important for text processing and also sometimes, we need to fix spelling, formatting, or unwanted characters before further analysis. The Python “string” is a sequence of Unicode characters in single or double quotes or even in triple quotes for multi-line strings. Python does not include a separate character type, so a string of length “1” is a character. Also, “strings” are immutable, meaning we cannot change, add or remove the characters once created.

Python’s blog tutorial examines different methods for replacing characters in a string.

How to Replace/Change Characters in a String?

To replace characters in the specified string, various methods are utilized in Python. Here are the methods we’ll discuss:

Method 1: Replace Characters in Python String Using the “string.replace()” Method

The “string.replace()” method is a way to replace one or more parts of a string with another string.

Syntax

string.replace(oldvalue, newvalue, count)

 

In the above syntax, “oldvalue” is the string to search for, “newvalue” is the string to replace with, and “count” is an optional number of occurrences to replace.

Example 1: Replace Sequence of Characters in a Given String

Let’s do so using the following example:

old_value = "Python"
new_value = "Java"
print(old_value.replace("Python", new_value))

 

In the above code, the “replace()” method takes the old and new values as its arguments, respectively, and replaces the specified value with the new value.

Output

Based on the above snippet, the specified sequence of characters has been replaced in the given string.

Example 2: Replace/Modify the Contained Multiple String Characters

Here is an example code:

old_value = "Python With ML or Python With AI "
new_value = "Java"
print(old_value.replace("Python", new_value, 1))

 

In the above code snippet, the “replace()” method is used to replace the specified characters indicated multiple times in the string by taking the third optional parameter “count”. The “count=1” specifies that the first occurrences of the previous value will be replaced/updated with the updated value.

Output

Only the first instances of the old value have been replaced with the new value in the above snippet accordingly.

Method 2: Replace Characters in Python String Using the “re.sub()” Method

The “re.sub()” function in Python is a built-in regex tool that finds and replaces a certain pattern in a string with another string or the output of a function and gives back the modified string.

Syntax

re.sub(pattern, repl, string, count=0, flags=0)

 

In the above syntax:

  • The “pattern” parameter specifies the regular expression to match.
  • The “repl” parameter specifies the replacement string or a function that retrieves the replacement string.
  • The “string” parameter is the input string to be searched and modified.
  • The “count” argument is the highest/maximum number of substitutions to be made (default is “0”, which means all occurrences).
  • The “flags” parameter defines the optional flags that modify the matching behavior (such as `re.IGNORECASE`, `re.MULTILINE`, etc.).

Example

The given code is used to replace characters in a string:

import re
value = "Python With ML or Python With AI"
print(re.sub("Python", "Java", value))

 

In the above code, the “re.sub()” method takes the old, new, and given strings as its arguments, respectively, and replaces the specified sequence of characters based on that.

Output

The above snippet verified that the specified sequence of characters has been replaced with the new characters.

Method 3: Replace Characters in Python String Using the “String Slicing” Technique

The method of string slicing in Python involves specifying the start and end indexes, along with an optional step size, to obtain a substring from a given string.

Syntax

string[start:end:step]

 

In the above syntax, “start” is the first character index to include, “end” is the index of the last character to exclude, and the “step” is the number of characters to skip between each slice.

Note: If “start” is missed, it defaults to “0” and if the “end” is omitted, it defaults to the string length and If a step is omitted, it defaults to “1”.

Example

The below code is utilized to replace/modify a character in a string:

string1 = "Python With ML or Python With AI"
index = 14
new_char = ","
string1 = string1[:index] + new_char + string1[index + 1:]
print(string1)

 

In the above code lines, the input string, index, and the new value are initialized at the start, respectively. After that, the “string slicing” technique is used to replace the old character “empty space” with the new initialized character “comma (,)”.

Output

Method 4: Replace Characters in Python String Utilizing the “for” Loop

The “for” loop is also utilized to replace character(s) in Python by iterating over the input string.

Example

Here is a sample code:

string1 = "Python With ML or Python With AI"
old_char = "P"
new_char = "J"
final_str = ""
for char in string1:
    if char == old_char:
        final_str += new_char
    else:
        final_str += char
print(final_str)

 

In this code, the input string, old, new, and an empty string is initialized, respectively. The “for” loop iterates over/through the input string and uses the “if/else” statement to replace a character in the string.

Output

The above snippet verified that the specified character from the given string at all the occurrences has been replaced with the new characters.

Conclusion

To replace characters or strings in the input string, the “string.replace()” method, “re.sub()” method, “String Slicing” technique, or the “for“ loop is used in Python. These approaches perform the desired functionality effectively. However, the “string.replace()” method takes the old, new and the count value and the “re.sub()” method takes the old, new, and input string as an augment to replace the characters in the string. This blog discussed multiple approaches to replacing/modifying characters in a string.

About the author

Talha Saif Malik

Talha is a contributor at Linux Hint with a vision to bring value and do useful things for the world. He loves to read, write and speak about Linux, Data, Computers and Technology.