Python: Replace all instances of a character in a string

The objective is to arrange a lowercase string in a way that the characters with their first occurrences are displayed first, along with all their subsequent occurrences. Multiple occurrences of characters in the string can be grouped together based on their first occurrences. This approach is particularly convenient due to the limited set of 26 possible characters in the given strings.


Given a string s and a character c, we need to determine if all instances of c are grouped together in s. If c is not found in s, the result should also be true.

If the input is similar to s = “bbbbaaaaaaaccddd” with c = ‘a’, the output will be True.

In order to address this issue, we will proceed by following the subsequent steps −

  • flag := False
  • index := 0
  • n := size of string
  • As long as the index is less than n, perform the following actions:
    1. Execute
  • if string[index] is same as c, then

    • if flag is True, then

      • return False
      • .
        2. Execute

      • while index < n and string[index] is same as c, do

        • index := index + 1
        • .
          3. Execute

        • flag := True
        • .
          4. Execute

        • otherwise,

          • index := index + 1
          • .

        • return True

        Take a look at the subsequent implementation in order to gain a clearer understanding.

        Example

        Live Demo

        def solve(string, c) :
           flag = False
           index = 0
           n = len(string)
           while index < n:
              if string[index] == c:
                 if (flag == True) :
                    return False
                 while index < n and string[index] == c:
                    index += 1
                 flag = True
              else :
                 index += 1
           return True
        s = "bbbbaaaaaaaccddd"
        c = 'a'
        print(solve(s, c))

        Input

        "bbbbaaaaaaaccddd", "a"

        Output

        True

Frequently Asked Questions