Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python Program to Replace all Occurrences of 'a' with $ in a String
When it is required to replace all the occurrences of 'a' with a character such as '$' in a string, Python provides multiple approaches. You can iterate through the string manually, use the built-in replace() method, or use string translation methods.
Method 1: Using Manual Iteration
This approach iterates through each character and builds a new string ?
my_str = "Jane Will Rob Harry Fanch Dave Nancy"
changed_str = ''
for char in range(0, len(my_str)):
if(my_str[char] == 'a'):
changed_str += '$'
else:
changed_str += my_str[char]
print("The original string is :")
print(my_str)
print("The modified string is : ")
print(changed_str)
The original string is : Jane Will Rob Harry Fanch Dave Nancy The modified string is : J$ne Will Rob H$rry F$nch D$ve N$ncy
Method 2: Using replace() Method
The built-in replace() method is the most straightforward approach ?
my_str = "Jane Will Rob Harry Fanch Dave Nancy"
changed_str = my_str.replace('a', '$')
print("The original string is :")
print(my_str)
print("The modified string is : ")
print(changed_str)
The original string is : Jane Will Rob Harry Fanch Dave Nancy The modified string is : J$ne Will Rob H$rry F$nch D$ve N$ncy
Method 3: Using List Comprehension
A more Pythonic approach using list comprehension and join() ?
my_str = "Jane Will Rob Harry Fanch Dave Nancy"
changed_str = ''.join(['$' if char == 'a' else char for char in my_str])
print("The original string is :")
print(my_str)
print("The modified string is : ")
print(changed_str)
The original string is : Jane Will Rob Harry Fanch Dave Nancy The modified string is : J$ne Will Rob H$rry F$nch D$ve N$ncy
Comparison
| Method | Readability | Performance | Best For |
|---|---|---|---|
| Manual Iteration | Good | Slower | Learning purposes |
| replace() | Excellent | Fastest | Simple replacements |
| List Comprehension | Good | Fast | Complex conditions |
Conclusion
The replace() method is the most efficient and readable approach for simple character replacements. Use list comprehension when you need more complex replacement logic, and manual iteration for educational purposes or when you need fine-grained control.
