Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Python - Replace multiple characters at once
Next article icon

Python – Replace Different Characters in String at Once

Last Updated : 29 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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 a string 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 dictionary d = {'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().

Table of Content

  • Using List Comprehension
  • Using Regular Expressions
  • Using str.replace()

Using List Comprehension

List comprehension is a simple way to create new lists 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 comprehension res = ''.join([d[char] if char in d else char for char in s])  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
import re  s = 'geeksforgeeks is best'  d = {'e': '1', 'b': '6', 'i': '4'}  # using re.sub() to replace characters res = re.sub('|'.join(re.escape(k) for k in d), lambda match: 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 string based on the dictionary. 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 loop res = s for key, value in d.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, the replace() method is called on res replacing all occurrences of key with value. After each replacement, the updated string is stored back in res.


Next Article
Python - Replace multiple characters at once
author
manjeet_04
Improve
Article Tags :
  • Python
  • Python Programs
  • Python string-programs
Practice Tags :
  • python

Similar Reads

  • Replace a String character at given index in Python
    In Python, strings are immutable, meaning they cannot be directly modified. We need to create a new string using various methods to replace a character at a specific index. Using slicingSlicing is one of the most efficient ways to replace a character at a specific index. [GFGTABS] Python s = "h
    2 min read
  • Python - Replace multiple characters at once
    Replacing multiple characters in a string is a common task in Python Below, we explore methods to replace multiple characters at once, ranked from the most efficient to the least. Using translate() with maketrans() translate() method combined with maketrans() is the most efficient way to replace mul
    2 min read
  • Remove Multiple Characters from a String in Python
    Removing multiple characters from a string in Python can be achieved using various methods, such as str.replace(), regular expressions, or list comprehensions. Each method serves a specific use case, and the choice depends on your requirements. Let’s explore the different ways to achieve this in det
    3 min read
  • Remove Character in a String at a Specific Index in Python
    Removing a character from a string at a specific index is a common task when working with strings and because strings in Python are immutable we need to create a new string without the character at the specified index. String slicing is the simplest and most efficient way to remove a character at a
    2 min read
  • Iterate over characters of a string in Python
    In this article, we will learn how to iterate over the characters of a string in Python. There are several methods to do this, but we will focus on the most efficient one. The simplest way is to use a loop. Let’s explore this approach. Using for loopThe simplest way to iterate over the characters in
    2 min read
  • Python - Characters Index occurrences in String
    Sometimes, while working with Python Strings, we can have a problem in which we need to check for all the characters indices. The position where they occur. This kind of application can come in many domains. Lets discuss certain ways in which this task can be performed. Method #1 : Using set() + reg
    6 min read
  • Python - Extract range characters from String
    Given a String, extract characters only which lie between given letters. Input : test_str = 'geekforgeeks is best', strt, end = "g", "s" Output : gkorgksiss Explanation : All characters after g and before s are retained. Input : test_str = 'geekforgeeks is best', strt, end = "g", "r" Output : gkorgk
    4 min read
  • Split String into List of characters in Python
    We are given a string and our task is to split this string into a list of its individual characters, this can happen when we want to analyze or manipulate each character separately. For example, if we have a string like this: 'gfg' then the output will be ['g', 'f', 'g']. Using ListThe simplest way
    2 min read
  • Remove Special Characters from String in Python
    When working with text data in Python, it's common to encounter strings containing unwanted special characters such as punctuation, symbols or other non-alphanumeric elements. For example, given the input "Data!@Science#Rocks123", the desired output is "DataScienceRocks123". Let's explore different
    2 min read
  • Python - Insert characters at start and end of a string
    In Python programming, a String is an immutable datatype. But sometimes there may come a situation where we may need to manipulate a string, say add a character to a string. Let’s start with a simple example to insert characters at the start and end of a String in Python. [GFGTABS] Python s = "
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
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