Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • 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
  • 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:
Replacing Characters in a String Using Dictionary in Python
Next article icon

Replacing Characters in a String Using Dictionary in Python

Last Updated : 05 Feb, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

In Python, we can replace characters in a string dynamically based on a dictionary. Each key in the dictionary represents the character to be replaced, and its value specifies the replacement. For example, given the string "hello world" and a dictionary {'h': 'H', 'o': 'O'}, the output would be "HellO wOrld". Let's explore several ways to achieve this.

Using str.translate() with str.maketrans()

This method uses Python's built-in str.translate() and str.maketrans() methods to replace characters efficiently.

Python
s = "hello world" replacements = {'h': 'H', 'o': 'O'}  # Create translation table and replace characters res = s.translate(str.maketrans(replacements))  print(res) 

Output
HellO wOrld 

Explanation:

  • str.maketrans() method creates a translation table from the dictionary.
  • str.translate() method applies the translation table to the string, replacing the specified characters.

Let's explore some more ways and see how we can replace characters in a string using dictionary in Python.

Table of Content

  • Using List Comprehension with join()
  • Using For Loop
  • Using Regular Expressions

Using List Comprehension with join()

We can iterate through the string and replace characters based on the dictionary using a list comprehension.

Python
s = "hello world" replacements = {'h': 'H', 'o': 'O'}  # Replace characters and join back to a string res = ''.join(replacements.get(c, c) for c in s)  print(res) 

Output
GFG!

Explanation:

  • The get method retrieves the replacement for a character if it exists in the dictionary; otherwise, it keeps the original character.
  • join() method combines the updated characters into a single string.

Using For Loop

This approach uses a traditional for loop to iterate through the string and replace characters.

Python
s = "hello world" replacements = {'h': 'H', 'o': 'O'}  res = ""  # Replace characters manually for c in s:     res += replacements.get(c, c)  print(res) 

Output
HellO wOrld 

Explanation:

  • for loop iterates through each character in the string.
  • Get method checks if the character has a replacement; otherwise, it appends the original character.

Using Regular Expressions

If the dictionary keys contain multiple characters or patterns, re.sub() can be used for replacements.

Python
import re  s = "hello world" replacements = {'h': 'H', 'o': 'O'}  # Create a regular expression pattern from the dictionary keys pattern = re.compile('|'.join(re.escape(k) for k in replacements))  # Replace characters using the pattern res = pattern.sub(lambda x: replacements[x.group(0)], s)  print(res) 

Output
HellO wOrld 

Explanation:

  • re.escape() method ensures special characters in the dictionary keys are escaped properly.
  • sub() method replaces matches with corresponding values from the dictionary.

Next Article
Replacing Characters in a String Using Dictionary in Python

K

khushidg6jy
Improve
Article Tags :
  • Python
  • python
Practice Tags :
  • python
  • python

Similar Reads

    How to replace words in a string using a dictionary mapping
    In Python, we often need to replace words in a string based on a dictionary mapping, where keys are words to replace and values are their replacements. For example, given the string "the quick brown fox jumps over the lazy dog" and the dictionary {"quick": "slow", "lazy": "active"}, we want to repla
    4 min read
    Create a Nested Dictionary from Text File Using Python
    We are given a text file and our task is to create a nested dictionary using Python. In this article, we will see how we can create a nested dictionary from a text file in Python using different approaches. Create a Nested Dictionary from Text File Using PythonBelow are the ways to Create Nested Dic
    3 min read
    Convert Unicode String to Dictionary in Python
    Python's versatility shines in its ability to handle diverse data types, with Unicode strings playing a crucial role in managing text data spanning multiple languages and scripts. When faced with a Unicode string and the need to organize it for effective data manipulation, the common task is convert
    2 min read
    Python - Replace all occurrences of a substring in a string
    Replacing all occurrences of a substring in a string means identifying every instance of a specific sequence of characters within a string and substituting it with another sequence of characters. Using replace()replace () method is the most straightforward and efficient way to replace all occurrence
    2 min read
    Map function and Lambda expression in Python to replace characters
    Given a string S, c1 and c2. Replace character c1 with c2 and c2 with c1. Examples: Input : str = 'grrksfoegrrks' c1 = e, c2 = r Output : geeksforgeeks Input : str = 'ratul' c1 = t, c2 = h Output : rahul We have an existing solution for this problem in C++. Please refer to Replace a character c1 wit
    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