On this page, we will see How to replace multiple characters in a string with a different Pythonic approach. However, there are many methods to replace characters in a string, from which replace() built-in function is our first approach. If you want to replace the multiple characters in a string sometimes you replace it with whitespace or sometimes with different characters or values. This page covers all the problems regarding replacing multiple characters in a string in Python.
If you want to learn more about Python Programming, Visit Python Programming Tutorials.
*Working on Jupyter Notebook Anaconda Environment
Using built-in replace() approach
A built-in Python function called replace() allows you to replace characters in strings. A Python function called replace () takes only three arguments (old string character, new string character, optional third argument), while the third option is count, which decides in a word how many characters you wish to replace.
Here in the following example, that elaborates how to use the built-in function replace().
- In a list the characters is initialized the order pair in a list execuates in aggregation with the replace() function.
- In order pair, the first entity is an old character that we want to replace, and the second entity is the modified character that overrides the old character in a string.
- The replacement characters need to be added to a list
- the characters in a string is replaced using the replace function.
- Using for in structure in aggregation with replace() function to perform operation of replacing multiple characters in a string in Python.
- The for loop iterate over an if… in structure and replace the characters from the old_string.
#creating a string
old_string = 'Entechin -Python tutorials'
replacing_multiple_chars = [('-', ' '), ('s', 's!')]
#intializing for..in strusture
for char, i in replacing_multiple_chars:
# condition
if char in old_string:
#using replace() method to replace multiple characters in a string
modified_string = old_string.replace(char, i)
#printing modified string
print(modified_string)
Entechin -Python tutorials!
Another approach:
The replacing multiple characters performs a useful task in mathematics. Let’s assume you have a bunch of strings with digits that you want to use for your project. But you want to replace the negative numbers with positive numbers and you have to replace the dash (-) character with ‘+ in all strings. Here you can do this job!
#creating a string
old_string = 'the positive number is: -1 -2 -3 -4'
#The replacement characters need to be added to a list
replacing_multiple_char = ["-", "+"]
#for..in structure
#The for loop iterate over an if… in structure and replace the characters from the old_string.
for i in replacing_multiple_char:
old_string = old_string.replace(i, '+')
#replace - character with a +
print(old_string)
the positive number is: +1 +2 +3 +4
Calling sub() function from regex module to replace multiple characters in a string in Python
Using regular expressions to search or replace strings characters. However, regular expression is a string, here in the following example converting special characters entities in a string into a readable string. The re module, helping on replacing multiple strings characters using regular expressions in Python.
Here is the execution process:
- Using Python’s re module, we can perform replacements with the given character by using the sub() function. An updated string is returned with the new characters inserted.
- With the meta characters ‘ | ‘, and the special characters “!, @, #…” replacement with new modified character in a string is performed.
# importing regex module from the library
import re
# multiple characters to be replaced
old_string = "\n0@1#2 3 4"
print("Original string: ", old_string)
#From the regex module, call the sub() function
# '|' used for either or
#Special sequence '/s' represents white space
# \n|@|#|\s all special characters are replaced with an new line, represented by special sequence'\n'
modified_string = re.sub("\n|@|#|\s", "\n", old_string)
print("Modified_String: ", modified_string)
Original string:
0@1#2 3 4
Modified_String:
0
1
2
3
4
Another approach:
Here the similar example code, we are replacing whitespace in a string with a new line. Here special sequence ‘/s’ represents whitespace. We are replacing the whitespace, with the special sequence ‘/n’ that helps us to print a string characters in new line, every times the whitespace occurs in a string, using sub() function.
# importing regex module from the library
import re
# multiple characters to be replaced
old_string = "\n0 1 2 3 4"
print("Original string: ", old_string)
#From the regex module, call the sub() function
#Special sequence '/s' represents white space
# \s special characters are replaced with an new line, represented by special sequence'\n'
modified_string = re.sub("\s", "\n", old_string)
print("Modified_String: ", modified_string)
Original string:
0 1 2 3 4
Modified_String:
0
1
2
3
4
Using maketrans() function with translate() to replace multiple characters in a string in Python
The replacement of multiple characters in a string is possible using built-in translate() function in aggregation with maketrans() function to perform the desired task. Dictionary containing the characters to replace and their replacements. This translate a string using the str.maketrans() method, by storing old and modified values in a dictionaries and thus in this way, replacing characters is easy with translate().
The execution performs in the following example as:
- The translation table was created by the help of a dictionary using translate() function.
- Following characters in string were replaced based on that translation table by the translate() method of Str,
- ‘-‘ becomes ‘:’.
- ‘p’ becomes ‘P’.
- ‘.’ becomes ‘s.’.
#creating a string
Original_string = "Entechin-python tutorial."
#using dictionary to Replace all multiple characters in a string
#in key: value structure of dictionary, pass the modified number, character in place of value
# and key will the character to be replaced, value will be the character to be replaced with
char_to_be_replaced = {'-': ' : ',
'p': 'P',
'.': 's.'}
# based on the above dictionary, using translate in aggregation with maketrans() function to perform a task
Modified_String = Original_string.translate(str.maketrans(char_to_be_replaced))
print(Modified_String)
Entechin : Python tutorials.
by handling with dictionary:
Here in a simple example demonstrate how dictionary replace multiple characters in a string in Python. The example execuates in the following manner:
- Creating a string
- pass the modified number, character in place of value, and key will the character to be replaced, value will be the character to be replaced with.
- For…in structure iterates over the if..in condition all over the string. During iteration, If condition satisfies, the item in dictionary are checked to be present in string,
- If yes then the key in dictionary in the string is replaced with the respective value and this will stores the result in the new empty string.
#creating a string
Original_string = "Entechin!Python@tutorials."
#using dictionary to Replace all multiple characters in a string
#in key: value structure of dictionary, pass the modified number, character in place of value
# and key will the character to be replaced, value will be the character to be replaced with
replacements_dict = { '!': ':\t',
'@': ' ',
}
#making a new empty string
new_string = ''
# for loop iterate through entire string characters
for i in Original_string:
#if condition checks and replace character is in dict as key with their respective value
if i in replacements_dict:
# If the condition satisfied then modifies the value of that key character in a string to modified string
new_string += replacements_dict[i]
else:
# If conditions disqualifies, then return the original string
new_string += i
print("new_string:", new_string)
new_string: Entechin: Python tutorials.
Conclusion
The purpose of this tutorial is to demonstrate how multiple characters can be replaced in a string. We have learnt what it is and then looked at the functions available in Python to handle such replacement. This can be used to do just about any kind of search and replace using regular expressions. This can be done using re module, and with replace() method, and dictionary to replace strings multiple characters with some other characters.