Replace Repeating Characters in a String – Python Program
Last updated 4 months ago | 163 views 75 5

String manipulation is a fundamental concept in programming, and today, we’ll explore an interesting problem:
✅ Given a string, replace all occurrences of its first character with '$', except for the first occurrence.
This simple yet powerful trick is widely used in text processing, data cleaning, and pattern matching tasks. Let’s dive into the implementation!
Python Solution
To achieve this, we will follow these steps:
- Extract the first character of the string.
- Replace all occurrences of this character in the rest of the string with '$'.
- Concatenate the unchanged first character with the modified rest of the string.
✅ Python Code Implementation
def replace_chars(s):
if len(s) == 0:
return s # Return empty string if input is empty
first_char = s[0] # Get the first character
modified_part = s[1:].replace(first_char, '$') # Replace occurrences in the rest of the string
return first_char + modified_part # Concatenate and return the result
# Example usage
print(replace_chars("restart")) # Output: resta$t
print(replace_chars("hello")) # Output: hello (no repeating characters)
print(replace_chars("abcabc")) # Output: abc$bc
print(replace_chars("a")) # Output: a (only one character)
print(replace_chars("")) # Output: (empty string)
How It Works?
Example 1: "restart"
- First character: 'r'
- Replace all 'r' except the first → "resta$t"
Example 2: "hello"
- First character: 'h'
- Replace all 'h' except the first → "hello" (no repeating characters)
Example 3: "abcabc"
- First character: 'a'
- Replace all 'a' except the first → "abc$bc"
Why Use This Approach?
✅ Simple & Efficient – Uses Python’s built-in .replace() method.
✅ Handles All Edge Cases – Works for empty strings and single-character inputs.
✅ Beginner-Friendly – Easy to understand and implement.
This string transformation technique is a handy trick for working with text processing, encoding schemes, and pattern replacements. Try it out and enhance your Python skills!