Python replace several characters

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.

Читайте также:  Compile java classes in eclipse

Источник

Python : How to replace single or multiple characters in a string ?

In this article we will discuss how to replace single or multiple characters in a string in Python.

Python provides a str.replace() function i.e.

It returns a new string object that is a copy of existing string with replaced content. Also,

  • If count is not provides then it will return a string with all the occurrences of ‘old’, replaced with ‘new’ string.
  • If count parameter is passed then it will return a string with first ‘count’ occurrences of ‘old’ string replaced with ‘new’ string.

Let’s understand by examples,

Frequently Asked:

Replace all occurrences of given character / string in a string

Suppose we have a string i.e.

mainStr = "Hello, This is a sample string"

Now, lets replace all the occurrences of ‘s’ with ‘X’ i.e.

''' Replace all occurrences of given character or string in main string ''' otherStr = mainStr.replace('s' , 'X')

Contents of otherStr is as follows,

Hello, ThiX iX a Xample Xtring

As strings are immutable in Python, so we can not change its content. Therefore member functions like replace() returns a new string.
As we have not provided the count parameter in replace() function. So, it will replace all the occurrences of ‘s’ with ‘X’. But what if we want to replace only first few occurrences instead of all? Let’s see how to do that,

Replace first n occurrences of given character / sub string in a string

Suppose we have a string i.e.

mainStr = "Hello, This is a sample string"

Now, lets replace first 2 occurrences of ‘s’ with ‘XXXS’ i.e.

''' Replace First 2 occurrences of given character or string in main string ''' otherStr = mainStr.replace('s' , 'XXXS', 2)

Contents of otherStr is as follows,

Hello, ThiXXXS iXXXS a sample string

As we have passed the count parameter as 2, so only first 2 occurrences of ‘s’ will be replaced in the returned copy.

Читайте также:  Run Javascript On Page Load

Replace multiple characters/strings in a string

str.replace() function can replace the occurrences of one given sub string only. But what if we want to replace multiple sub strings in a given string ?

Suppose we have a string i.e.

mainStr = "Hello, This is a sample string"

Now, how to replace all the occurrences of these three characters ‘s’, ‘l’, ‘a’ with this string ‘AA’ ?
Let’s create a new function over replace() to do that i.e.

''' Replace a set of multiple sub strings with a new string in main string. ''' def replaceMultiple(mainString, toBeReplaces, newString): # Iterate over the strings to be replaced for elem in toBeReplaces : # Check if string is in the main string if elem in mainString : # Replace the string mainString = mainString.replace(elem, newString) return mainString

It will replace all the occurrences of strings in List toBeReplaces with newString in the main given list mainString.
Let’s see how to replace the occurrences of [‘s’, ‘l’, ‘a’] with “AA” i.e.

''' Replace multiple characters / strings from a string ''' # Replace all the occurrences of string in list by AA in the main list otherStr = replaceMultiple(mainStr, ['s', 'l', 'a'] , "AA")

Contents of otherStr is as follows,

HeAAAAo, ThiAA iAA AA AAAAmpAAe AAtring

Complete example is as follows,

''' Replace a set of multiple sub strings with a new string in main string. ''' def replaceMultiple(mainString, toBeReplaces, newString): # Iterate over the strings to be replaced for elem in toBeReplaces : # Check if string is in the main string if elem in mainString : # Replace the string mainString = mainString.replace(elem, newString) return mainString def main(): mainStr = "Hello, This is a sample string" ''' Replace all occurrences of given character or string in main string ''' otherStr = mainStr.replace('s' , 'X') print("String with replaced Content : " , otherStr) ''' Replace First 2 occurrences of given character or string in main string ''' otherStr = mainStr.replace('s' , 'XXXS', 2) print(otherStr) ''' Replace multiple characters / strings from a string ''' # Replace all the occurrences of string in list by AA in the main list otherStr = replaceMultiple(mainStr, ['s', 'l', 'a'] , "AA") print(otherStr) if __name__ == '__main__': main()
String with replaced Content : Hello, ThiX iX a Xample Xtring Hello, ThiXXXS iXXXS a sample string HeAAAAo, ThiAA iAA AA AAAAmpAAe AAtring

Источник

Оцените статью