. Advertisement .
..3..
. Advertisement .
..4..
Struggling to replace multiple characters in a string in Python? ITtutoria is delighted to step in and lend you a hand. Here are three streamlined approaches that you may employ for this task!
How to Replace Multiple Characters in A String in Python
1. Use Replace()
The String variant (Str) is a critical class in Python. It offers a technique substitute to alter substrings in a primary string. What does that mean? This approach will extract all current substring occurrences and replace them with a new substring.
Character data category is not a prevalent concept in Python. Hence, we might regard one single character as a string. Therefore, Replace () is a plausible tactic to substitute more than one character in the main string.
Codes:
sampleString = "How to replace multiple characters in a string in Python"
characterReplace = {'t': 'T',
'r': 'R',
'm': 'M',
's': 'S'}
# Iterate over all key-value pairs in dictionary
for key, value in characterReplace.items():
# Replace key character with value character in string
sampleString = sampleString.replace(key, value)
print(sampleString)
Outputs:
How To Replace MulTiple chaRacTeRS in a STRing in PyThon
In these examples, all the following occurrences have been replaced:
- ‘t’ is substituted by ‘T.’
- ‘r’ is substituted by ‘R.’
- ‘m’ is substituted by ‘M.’
- ‘s’ is substituted by ‘S.’
All these Python strings are immutable. As a result, changing their contents is not feasible, and the Replace() operation sends back our string copy with substituted values.
2. Use Maketrans() and Translate()
Maketrans() and Translate() employ a slightly different tactic. They operate on dictionaries to map out routes from old values to new ones.
Maketrans() is compatible with three parameters (or a sole mapping dictionary):
- str1 represents the character string that you are about to replace.
- str2 is the replacement string for the above characters
- str3 refers to a string you mean to delete.
In short, Maketrans() delivers a mapping board between the initial strings and their substitutes. In the same vein, Translate()receives any value that Maketrans() sends back. Once done, it will generate a translated string.
Suppose you wish to convert lowercase vowels into uppercase in the following example. All x,z, and y identified in that string should get deleted.
text_sample = "How to replace multiple characters in a string in Python"
def processString5(text_sample):
trans_table = text_sample.maketrans("amsl", "AMSL", "stc")
text_sample = text_sample.translate(trans_table)
print(text_sample)
processString5(text_sample)
Outputs:
How o repLAe MuLipLe hArAer in A ring in Pyhon
The Translate() function has successfully transformed all lower cases into uppercases. Every instance of x, z, and y is removed.
3. Use RegEx
RegEx (Regular Expression) is also an easy and popular tactic to replace multiple characters in a string in Python. We might employ it to create a correspondence with the white space. Once done, extract them by the Re.sub() function.
# Python code to replace multiple characters at once with help of regex function
import re
# initializing string
sample_String = "How to replace multiple characters in a string in Python"
# printing original string
print("The original string is : " + str(sample_String))
replace_char = {'t': 'T',
'm': 'M',
'i': 'I',
'c': 'C'}
# Replace multiple characters using regex
sample_String = re.sub(r"[tmic]",
lambda x: replace_char[x.group(0)],
sample_String)
print("New string after replacement of characters : " + sample_String)
Outputs:
The original string is : How to replace multiple characters in a string in Python
New string after replacement of characters : How To replaCe MulTIple CharaCTers In a sTrIng In PyThonThAs As tBstACg strACg
FAQs
1. How Can I Include A Character in My String in The First Place?
Join (), f-strings, and Format() are three prominent functions for character inclusion. For more instructions and examples, please refer to this instructional article.
2. Is It Possible to Strip More Than One Character?
Yes, with the help of the Strip() function. By default, it extracts the whitespace from the starting point (leading) and endpoint (trailing). Once you deduce an argument as “character”, Strip() will delete it right away.
Conclusion
This tutorial has presented three optimal methods in response to your question, “How to replace multiple characters in a string in Python?”. We hope our detailed guidelines and examples are of great assistance. Write to us if there are questions!
3 Comments