Movatterモバイル変換


[0]ホーム

URL:


Open In App

The task is to replace multiple different characters in a string simultaneously based on a given mapping. For example, given the string: s = "hello world" and replacements = {'h': 'H', 'o': '0', 'd': 'D'} after replacing the specified characters, the result will be: "Hell0 w0rlD"

Using str.translate()

str.translate()method in Python efficiently replaces characters in astring based on a translation table created using str.maketrans(). str.maketrans()generates a mapping of characters to their replacements while str.translate() applies this mapping to transform the string.

Python
s='geeksforgeeks is best'# Initializing mapping dictionaryd={'e':'1','b':'6','i':'4'}# Using translate() with maketrans()res=s.translate(str.maketrans(d))print(res)

Output
g11ksforg11ks 4s 61st

Explanation:

  • str.maketrans(d) converts the dictionary d into a translation table that maps characters to their replacements.
  • s.translate(str.maketrans(d)) applies the translation table to string s using translate().

Using List Comprehension

List comprehension is a simple way to create newlists by applying an expression to each item. For string manipulation, it conditionally replaces characters eliminating the need for loops and making the code cleaner and more readable.

Python
s='geeksforgeeks is best'd={'e':'1','b':'6','i':'4'}# Replacing characters using list comprehensionres=''.join([d[char]ifcharindelsecharforcharins])print(res)

Output
g11ksforg11ks 4s 61st

Explanation:

  • List comprehension iterates over each character in s and if the character is found in the dictionary d. It is replaced with its mapped value otherwise the character remains unchanged.
  • ''.join([...]) combines the transformed list of characters back into a single string.

Using Regular Expressions

This method uses re.sub() function from Python's re module to replace characters in a string. It allows us to define a pattern to match characters and replace them efficiently. This is a flexible approach, especially when working with multiple replacements in one go.

Python
importres='geeksforgeeks is best'd={'e':'1','b':'6','i':'4'}# using re.sub() to replace charactersres=re.sub('|'.join(re.escape(k)forkind),lambdamatch:d[match.group(0)],s)print(res)

Output
g11ksforg11ks 4s 61st

Explanation:

  • '|'.join(re.escape(k) for k in d) creates a regular expression that matches any of the keys from the dictionary ('e', 'b', and 'i').
  • lambda anonymous function returns the corresponding mapped value from the dictionary d for each match.
  • re.sub() applies the substitution to the string, replacing characters based on the dictionary mapping.

Using str.replace()

This method iterates over a small mapping dictionary, using str.replace()to replace characters in the stringbased on thedictionary. It’s simple and effective for small-scale replacements, but can be less efficient for larger strings or complex replacements.

Python
s='geeksforgeeks is best'd={'e':'1','b':'6','i':'4'}# using replace() in a loopres=sforkey,valueind.items():res=res.replace(key,value)print(res)

Output
g11ksforg11ks 4s 61st

Explanation:

  • res = s: variable res is initialized with the value of s .
  • for key, value in d.items() iterates through each key-value pair in the dictionary d. For each pair, the loop performs a replacement in the string.
  • res = res.replace(key, value) here in each iteration, thereplace()method is called on res replacing all occurrences of key with value. After each replacement, the updated string is stored back in res.

Improve

Explore

Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences

[8]ページ先頭

©2009-2025 Movatter.jp