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 - All occurrences of substring in string
Next article icon

Python Program to Replace all Occurrences of ‘a’ with $ in a String

Last Updated : 18 Apr, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a string, the task is to write a Python program to replace all occurrence of ‘a’ with $.

Examples:

Input: Ali has all aces Output: $li h$s $ll $ces  Input: All Exams are over Output: $ll Ex$ms $re Over

Method 1:  uses splitting of the given specified string into a set of characters. An empty string variable is used to store modified string . We loop over the character array and check if the character at this index is equivalent to ‘a’ , and then append ‘$’ sign, in case the condition is satisfied. Otherwise, the original character is copied into the new string.  

Python3




# declaring a string variable
str = "Amdani athani kharcha rupaiya."
 
# declaring an empty string variable for storing modified string
modified_str = ''
 
# iterating over the string
for char in range(0, len(str)):
    # checking if the character at char index is equivalent to 'a'
    if(str[char] == 'a' or str[char] == 'a'.upper()):
        # append $ to modified string
        modified_str += '$'
    else:
        # append original string character
        modified_str += str[char]
 
print("Modified string : ")
print(modified_str)
 
 

Output:

Modified string : $md$ni $th$ni kh$rch$ rup$iy$.

Time Complexity: O(n), where n is length of str string.

Auxiliary Space: O(n), where n is length of modified_str string to store result.

Method 2: uses the inbuilt method replace() to replace all the occurrences of a particular character in the string with the new specified character. The method has the following syntax : 

replace( oldchar , newchar)

This method doesn’t change the original string, and the result has to be explicitly stored in the String variable. 

Python3




# declaring a string variable
str = "An apple A day keeps doctor Away."
 
# replacing character a with $ sign
str = str.replace('a', '$')
str = str.replace('a'.upper(),'$')
print("Modified string : ")
print(str)
 
 
Output
Modified string :  $n $pple $ d$y keeps doctor $w$y.

Time Complexity: O(n)
Auxiliary Space: O(n)

Method 3: Using Python re module

The re.sub() function from the re module is used to replace all occurrences of a particular pattern in a string with a specified replacement. In this case, we are using the pattern ‘a’ and the replacement ‘$’ to replace all occurrences of ‘a’ in the string str. The result of the re.sub() function is stored in the variable modified_str.
 

Python3




import re
 
#declaring a string variable
str = "Amdani athani kharcha rupaiya."
 
#using re.sub() function to replace all occurrences of 'a' with '$'
modified_str = re.sub("a", "$", str.lower())
 
#print("Modified string : ")
print(modified_str)
 
 
Output
$md$ni $th$ni kh$rch$ rup$iy$.

Time Complexity: O(n)
Auxiliary Space: O(n)

Method 4: Using list comprehension:

This approach uses a list comprehension to iterate over each character in the lowercase version of the input string str. If the character is equal to ‘a’, it is replaced with a ‘$’ symbol. Otherwise, the original character is used. The resulting list of characters is then joined back into a string using the join() method.

Python3




# declaring a string variable
str = "Amdani athani kharcha rupaiya."
 
# using list comprehension to replace all occurrences of 'a' with '$'
modified_str = ''.join(['$' if c == 'a' else c for c in str.lower()])
 
# print modified string
print(modified_str)
 
 
Output
$md$ni $th$ni kh$rch$ rup$iy$.

Time complexity: O(n), where n is the length of the input string.
Auxiliary space: O(n).



Next Article
Python - All occurrences of substring in string

Y

yashkumar0457
Improve
Article Tags :
  • Python
  • Python Programs
  • Python string-programs
Practice Tags :
  • python

Similar Reads

  • Python - All occurrences of substring in string
    A substring is a contiguous occurrence of characters within a string. Identifying all instances of a substring is important for verifying various tasks. In this article, we will check all occurrences of a substring in String. Using re.finditer()re.finditer() returns an iterator yielding match object
    3 min read
  • Python - Replace duplicate Occurrence in String
    Sometimes, while working with Python strings, we can have problem in which we need to perform the replace of a word. This is quite common task and has been discussed many times. But sometimes, the requirement is to replace occurrence of only duplicate, i.e from second occurrence. This has applicatio
    6 min read
  • Python Regex | Program to accept string ending with alphanumeric character
    Prerequisite: Regular expression in PythonGiven a string, write a Python program to check whether the given string is ending with only alphanumeric character or Not.Examples: Input: ankitrai326 Output: Accept Input: ankirai@ Output: Discard In this program, we are using search() method of re module.
    2 min read
  • Python Program to Replace Text in a File
    In this article, we are going to replace Text in a File using Python. Replacing Text could be either erasing the entire content of the file and replacing it with new text or it could mean modifying only specific words or sentences within the existing text. Method 1: Removing all text and write new t
    3 min read
  • Python | Replace multiple occurrence of character by single
    Given a string and a character, write a Python program to replace multiple occurrences of the given character by a single character. Examples: Input : Geeksforgeeks, ch = 'e' Output : Geksforgeks Input : Wiiiin, ch = 'i' Output : WinReplace multiple occurrence of character by singleApproach #1 : Nai
    4 min read
  • Get Second Occurrence of Substring in Python String
    We are given a string and a substring, and our task is to find the index of the second occurrence of that substring within the string. This means we need to identify not just if the substring exists, but where it appears for the second time. For example, if we have a string like "hello world, hello
    2 min read
  • Python program to convert camel case string to snake case
    Camel case is a writing style in which multiple words are concatenated into a single string, Snake case is another writing style where words are separated by underscores (_) and all letters are lowercase. We are going to cover how to convert camel case into snake case. Using Regular Expressions (re.
    3 min read
  • Python Program to Replace Specific Line in File
    In this article, we are going to write a Python program to replace specific lines in the file. We will first open the file in read-only mode and read all the lines using readlines(), creating a list of lines storing it in a variable. We will make the necessary changes to a specific line and after th
    2 min read
  • Python program to Replace all Characters of a List Except the given character
    Given a List. The task is to replace all the characters of the list with N except the given character. Input : test_list = ['G', 'F', 'G', 'I', 'S', 'B', 'E', 'S', 'T'], repl_chr = '*', ret_chr = 'G' Output : ['G', '*', 'G', '*', '*', '*', '*', '*', '*'] Explanation : All characters except G replace
    4 min read
  • Python program to remove last N characters from a string
    In this article, we’ll explore different ways to remove the last N characters from a string in Python. This common string manipulation task can be achieved using slicing, loops, or built-in methods for efficient and flexible solutions. Using String SlicingString slicing is one of the simplest and mo
    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