- Replace Multiple Characters in a String in Python
- Using built-in replace() approach
- Another approach:
- Calling sub() function from regex module to replace multiple characters in a string in Python
- Another approach:
- Using maketrans() function with translate() to replace multiple characters in a string in Python
- by handling with dictionary:
- Conclusion
- Related Posts:
- Python | Replace multiple occurrence of character by single
- Python3
- Python3
- Method#3: Using itertools.groupby
- Approach
- Algorithm
- Replace Multiple Characters in a String in Python
- Use str.replace() to Replace Multiple Characters in Python
Replace Multiple Characters in a String in Python
On this page, we will see How to replace multiple characters in a string with a different pythonic approaches. However, there are many methods to replace a characters in a string, from which replace() buit-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 a different characters or values. This page covers all the problem 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 elaborate 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 replace() function.
- In order pair the first entity is 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 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.
- 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 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 = # 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:
- 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.
Related Posts:
Python | Replace multiple occurrence of character by single
Given a string and a character, write a Python program to replace multiple occurrences of the given character by a single character.
Input : Geeksforgeeks, ch = 'e' Output : Geksforgeks Input : Wiiiin, ch = 'i' Output : Win
Approach #1 : Naive Approach This method is a brute force approach in which we take another list ‘new_str’. Use a for loop to check if the given character is repeated or not. If repeated multiple times, append the character single time to the list. Other characters(Not the given character) are simply appended to the list without any alteration.
Python3
Time Complexity: O(N)
Auxiliary Space: O(N)
Approach #2 : Using Python Regex
Python3
Time Complexity: O(N)
Auxiliary Space: O(1)
Method#3: Using itertools.groupby
Approach
In this approach, we use the groupby function to group consecutive characters in the string. We then iterate over the groups and check if the current group consists of the given character. If so, we add only one occurrence of that character to the new string. Otherwise, we add all the characters in the group to the new string. Finally, we return the new string with consecutive occurrences of the given character replaced by a single occurrence.
Algorithm
1. Import the groupby function from the itertools module.
2. Define a function named replace_multiple_occurrence that takes two arguments: string and ch.
3. Use the groupby function to group consecutive characters in the string into tuples of the form (key, group), where key is the character and group is an iterator over the consecutive occurrences of that character.
4. Initialize an empty string named new_str.
5. Iterate over the groups using a for loop.
6. For each group, check if the key is equal to the given character ch.
7. If the key is equal to ch, add only one occurrence of ch to the new_str.
8. If the key is not equal to ch, add all the characters in the group to the new_str.
9. Finally, return the new_str with consecutive occurrences of ch replaced by a single occurrence.
Replace Multiple Characters in a String in Python
- Use str.replace() to Replace Multiple Characters in Python
- Use re.sub() or re.subn() to Replace Multiple Characters in Python
- translate() and maketrans() to Replace Multiple Characters in Python
This tutorial shows you how to replace multiple characters in a string in Python.
Let’s say we want to remove special characters in a string and replace them with whitespace.
- The list of special characters to be removed would be !#$%^&*() .
- Also, we want to replace commas , with whitespace.
- The sample text that we will manipulate:
A. Quick,brown#$,fox,ju%m%^ped,ov&er&),th(e*,lazy,d#!og$$$
Use str.replace() to Replace Multiple Characters in Python
We can use the replace() method of the str data type to replace substrings into a different output.
replace() accepts two parameters, the first parameter is the regex pattern you want to match strings with, and the second parameter is the replacement string for the matched strings.
It also a third optional parameter in replace() which accepts an integer to set the maximum count of replacements to execute. If you put 2 as a count parameter, the replace() function will only match and replace 2 instances within the string.
str.replace(‘Hello’, ‘Hi’) will replace all instances of Hello in a string with Hi . If you have a string Hello World and run the replace function to it, it would become Hi World after execution.
Let’s use replace on the sample text that we declared above. First removing the special characters by looping each character and replacing them with an empty string, then converting commas into whitespace.
txt = "A. Quick,brown#$,fox,ju%m%^ped,ov&er&),th(e*,lazy,d#!og$$$" def processString(txt): specialChars = "!#$%^&*()" for specialChar in specialChars: txt = txt.replace(specialChar, '') print(txt) # A,Quick,brown,fox,jumped,over,the,lazy,dog txt = txt.replace(',', ' ') print(txt) # A Quick brown fox jumped over the lazy dog
That means anything within the square bracket of spChars will be replaced by an empty string using txt.replace(spChars, ») .
The string result of the first replace() function would then be: