Replace all occurrences in string but the first one











up vote
2
down vote

favorite
1












Given the string:




X did something. X found it to be good, and so X went home.




I would like to replace all occurrences of X but the first one, with Y, such that the output string would look like:




X did something. Y found it to be good, and so Y went home.




I tried many regex patterns (based on https://vi.stackexchange.com/questions/10905/substitution-how-to-ignore-the-nth-first-occurrences-of-a-pattern) but failed to implement this with Python










share|improve this question




























    up vote
    2
    down vote

    favorite
    1












    Given the string:




    X did something. X found it to be good, and so X went home.




    I would like to replace all occurrences of X but the first one, with Y, such that the output string would look like:




    X did something. Y found it to be good, and so Y went home.




    I tried many regex patterns (based on https://vi.stackexchange.com/questions/10905/substitution-how-to-ignore-the-nth-first-occurrences-of-a-pattern) but failed to implement this with Python










    share|improve this question


























      up vote
      2
      down vote

      favorite
      1









      up vote
      2
      down vote

      favorite
      1






      1





      Given the string:




      X did something. X found it to be good, and so X went home.




      I would like to replace all occurrences of X but the first one, with Y, such that the output string would look like:




      X did something. Y found it to be good, and so Y went home.




      I tried many regex patterns (based on https://vi.stackexchange.com/questions/10905/substitution-how-to-ignore-the-nth-first-occurrences-of-a-pattern) but failed to implement this with Python










      share|improve this question















      Given the string:




      X did something. X found it to be good, and so X went home.




      I would like to replace all occurrences of X but the first one, with Y, such that the output string would look like:




      X did something. Y found it to be good, and so Y went home.




      I tried many regex patterns (based on https://vi.stackexchange.com/questions/10905/substitution-how-to-ignore-the-nth-first-occurrences-of-a-pattern) but failed to implement this with Python







      python regex






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 10 at 14:54









      petezurich

      3,30381631




      3,30381631










      asked Nov 10 at 14:29









      Amit

      1,22711132




      1,22711132
























          6 Answers
          6






          active

          oldest

          votes

















          up vote
          6
          down vote



          accepted










          str.partition splits a string into the part before a delimiter, the delimiter itself, and the part after, or the string and two empty strings if the delimiter doesn’t exist. What that comes down to is:



          s = 'X did something. X found it to be good, and so X went home.'
          before, first, after = s.partition('X')
          result = before + first + after.replace('X', 'Y')





          share|improve this answer




























            up vote
            5
            down vote













            You cold use the fact that re.sub uses a function:



            import re


            def repl(match, count=[0]):
            x, = count
            count[0] += 1
            if x > 0:
            return 'Y'
            return 'X'


            print(re.sub('X', repl, 'X did something. X found it to be good, and so X went home.'))


            Output



            X did something. Y found it to be good, and so Y went home.


            The idea is to use a function that keeps the count of seen X and then replace it when the count if above 1.






            share|improve this answer




























              up vote
              2
              down vote













              Another Option is to find the first one and only after replace all X occurrences.



              Finally, concat the beginning to the start of the sentence



              st = 'X did something. X found it to be good, and so X went home.'
              first_found = st.find('X')
              print (st[:first_found + 1] + st[first_found + 1:].replace('X', 'Y'))
              # X did something. Y found it to be good, and so Y went home.





              share|improve this answer




























                up vote
                2
                down vote













                Here's a low tech solution without regex. :)



                >>> s = 'X did something. X found it to be good, and so X went home'
                >>> s = s.replace('X', 'Y').replace('Y', 'X', 1)
                >>> s
                >>> 'X did something. Y found it to be good, and so Y went home'


                Solution if 'Y' can exist in the original string:



                def replace_tail(s, target, replacement):
                try:
                pos = s.index(target)
                except ValueError:
                return s
                pos += len(target)
                head = s[:pos]
                tail = s[pos:]
                return head + tail.replace(target, replacement)


                Demo:



                >>> s = 'Today YYY and XXX did something. XXX found it to be good, and so XXX went home without YYY.'
                >>> replace_tail(s, 'XXX', 'YYY')
                >>> 'Today YYY and XXX did something. YYY found it to be good, and so YYY went home without YYY.'





                share|improve this answer



















                • 2




                  Gonna run in to trouble if a Y already existed before the X.
                  – Ry-
                  Nov 10 at 14:33










                • @Ry- correct! Amit, can you clarify if this can happen? I might have to increase the tech level a bit.
                  – timgeb
                  Nov 10 at 14:35






                • 1




                  Nice catch, In my use case, this can never happen. I like all of the proposed solutions, but this one is most elegant.
                  – Amit
                  Nov 10 at 14:38










                • @Amit in any case, I added a function that works in both scenarios.
                  – timgeb
                  Nov 10 at 14:47


















                up vote
                1
                down vote













                Apply iteratively the regex after finding the first match over the remaining of the string. Or just using replace if it is possible.






                share|improve this answer




























                  up vote
                  1
                  down vote













                  We can use slicing to produce two string: first one up to (and including) the first element, and the next slice that contains the rest. We can then apply the replace part on that part, and merge these back:



                  def replace_but_first(text, search, replace):
                  try:
                  idx = text.index(search) + len(search)
                  return text[:idx] + text[idx:].replace(search, replace)
                  except ValueError: # we did not found a single match
                  return text


                  For example:



                  >>> replace_but_first('X did something. X found it to be good, and so X went home.', 'X', 'Y')
                  'X did something. Y found it to be good, and so Y went home.'





                  share|improve this answer























                  • @Ry-: sorry I was confused between index and find.
                    – Willem Van Onsem
                    Nov 10 at 14:40










                  • .find() strilcty speaking will work as well, although this is a bit ugly, and we save some cycles by not doing a second iteration over the string.
                    – Willem Van Onsem
                    Nov 10 at 14:41











                  Your Answer






                  StackExchange.ifUsing("editor", function () {
                  StackExchange.using("externalEditor", function () {
                  StackExchange.using("snippets", function () {
                  StackExchange.snippets.init();
                  });
                  });
                  }, "code-snippets");

                  StackExchange.ready(function() {
                  var channelOptions = {
                  tags: "".split(" "),
                  id: "1"
                  };
                  initTagRenderer("".split(" "), "".split(" "), channelOptions);

                  StackExchange.using("externalEditor", function() {
                  // Have to fire editor after snippets, if snippets enabled
                  if (StackExchange.settings.snippets.snippetsEnabled) {
                  StackExchange.using("snippets", function() {
                  createEditor();
                  });
                  }
                  else {
                  createEditor();
                  }
                  });

                  function createEditor() {
                  StackExchange.prepareEditor({
                  heartbeatType: 'answer',
                  convertImagesToLinks: true,
                  noModals: true,
                  showLowRepImageUploadWarning: true,
                  reputationToPostImages: 10,
                  bindNavPrevention: true,
                  postfix: "",
                  imageUploader: {
                  brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
                  contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
                  allowUrls: true
                  },
                  onDemand: true,
                  discardSelector: ".discard-answer"
                  ,immediatelyShowMarkdownHelp:true
                  });


                  }
                  });














                   

                  draft saved


                  draft discarded


















                  StackExchange.ready(
                  function () {
                  StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53239936%2freplace-all-occurrences-in-string-but-the-first-one%23new-answer', 'question_page');
                  }
                  );

                  Post as a guest
































                  6 Answers
                  6






                  active

                  oldest

                  votes








                  6 Answers
                  6






                  active

                  oldest

                  votes









                  active

                  oldest

                  votes






                  active

                  oldest

                  votes








                  up vote
                  6
                  down vote



                  accepted










                  str.partition splits a string into the part before a delimiter, the delimiter itself, and the part after, or the string and two empty strings if the delimiter doesn’t exist. What that comes down to is:



                  s = 'X did something. X found it to be good, and so X went home.'
                  before, first, after = s.partition('X')
                  result = before + first + after.replace('X', 'Y')





                  share|improve this answer

























                    up vote
                    6
                    down vote



                    accepted










                    str.partition splits a string into the part before a delimiter, the delimiter itself, and the part after, or the string and two empty strings if the delimiter doesn’t exist. What that comes down to is:



                    s = 'X did something. X found it to be good, and so X went home.'
                    before, first, after = s.partition('X')
                    result = before + first + after.replace('X', 'Y')





                    share|improve this answer























                      up vote
                      6
                      down vote



                      accepted







                      up vote
                      6
                      down vote



                      accepted






                      str.partition splits a string into the part before a delimiter, the delimiter itself, and the part after, or the string and two empty strings if the delimiter doesn’t exist. What that comes down to is:



                      s = 'X did something. X found it to be good, and so X went home.'
                      before, first, after = s.partition('X')
                      result = before + first + after.replace('X', 'Y')





                      share|improve this answer












                      str.partition splits a string into the part before a delimiter, the delimiter itself, and the part after, or the string and two empty strings if the delimiter doesn’t exist. What that comes down to is:



                      s = 'X did something. X found it to be good, and so X went home.'
                      before, first, after = s.partition('X')
                      result = before + first + after.replace('X', 'Y')






                      share|improve this answer












                      share|improve this answer



                      share|improve this answer










                      answered Nov 10 at 14:36









                      Ry-

                      165k36334355




                      165k36334355
























                          up vote
                          5
                          down vote













                          You cold use the fact that re.sub uses a function:



                          import re


                          def repl(match, count=[0]):
                          x, = count
                          count[0] += 1
                          if x > 0:
                          return 'Y'
                          return 'X'


                          print(re.sub('X', repl, 'X did something. X found it to be good, and so X went home.'))


                          Output



                          X did something. Y found it to be good, and so Y went home.


                          The idea is to use a function that keeps the count of seen X and then replace it when the count if above 1.






                          share|improve this answer

























                            up vote
                            5
                            down vote













                            You cold use the fact that re.sub uses a function:



                            import re


                            def repl(match, count=[0]):
                            x, = count
                            count[0] += 1
                            if x > 0:
                            return 'Y'
                            return 'X'


                            print(re.sub('X', repl, 'X did something. X found it to be good, and so X went home.'))


                            Output



                            X did something. Y found it to be good, and so Y went home.


                            The idea is to use a function that keeps the count of seen X and then replace it when the count if above 1.






                            share|improve this answer























                              up vote
                              5
                              down vote










                              up vote
                              5
                              down vote









                              You cold use the fact that re.sub uses a function:



                              import re


                              def repl(match, count=[0]):
                              x, = count
                              count[0] += 1
                              if x > 0:
                              return 'Y'
                              return 'X'


                              print(re.sub('X', repl, 'X did something. X found it to be good, and so X went home.'))


                              Output



                              X did something. Y found it to be good, and so Y went home.


                              The idea is to use a function that keeps the count of seen X and then replace it when the count if above 1.






                              share|improve this answer












                              You cold use the fact that re.sub uses a function:



                              import re


                              def repl(match, count=[0]):
                              x, = count
                              count[0] += 1
                              if x > 0:
                              return 'Y'
                              return 'X'


                              print(re.sub('X', repl, 'X did something. X found it to be good, and so X went home.'))


                              Output



                              X did something. Y found it to be good, and so Y went home.


                              The idea is to use a function that keeps the count of seen X and then replace it when the count if above 1.







                              share|improve this answer












                              share|improve this answer



                              share|improve this answer










                              answered Nov 10 at 14:35









                              Daniel Mesejo

                              7,8541921




                              7,8541921






















                                  up vote
                                  2
                                  down vote













                                  Another Option is to find the first one and only after replace all X occurrences.



                                  Finally, concat the beginning to the start of the sentence



                                  st = 'X did something. X found it to be good, and so X went home.'
                                  first_found = st.find('X')
                                  print (st[:first_found + 1] + st[first_found + 1:].replace('X', 'Y'))
                                  # X did something. Y found it to be good, and so Y went home.





                                  share|improve this answer

























                                    up vote
                                    2
                                    down vote













                                    Another Option is to find the first one and only after replace all X occurrences.



                                    Finally, concat the beginning to the start of the sentence



                                    st = 'X did something. X found it to be good, and so X went home.'
                                    first_found = st.find('X')
                                    print (st[:first_found + 1] + st[first_found + 1:].replace('X', 'Y'))
                                    # X did something. Y found it to be good, and so Y went home.





                                    share|improve this answer























                                      up vote
                                      2
                                      down vote










                                      up vote
                                      2
                                      down vote









                                      Another Option is to find the first one and only after replace all X occurrences.



                                      Finally, concat the beginning to the start of the sentence



                                      st = 'X did something. X found it to be good, and so X went home.'
                                      first_found = st.find('X')
                                      print (st[:first_found + 1] + st[first_found + 1:].replace('X', 'Y'))
                                      # X did something. Y found it to be good, and so Y went home.





                                      share|improve this answer












                                      Another Option is to find the first one and only after replace all X occurrences.



                                      Finally, concat the beginning to the start of the sentence



                                      st = 'X did something. X found it to be good, and so X went home.'
                                      first_found = st.find('X')
                                      print (st[:first_found + 1] + st[first_found + 1:].replace('X', 'Y'))
                                      # X did something. Y found it to be good, and so Y went home.






                                      share|improve this answer












                                      share|improve this answer



                                      share|improve this answer










                                      answered Nov 10 at 14:39









                                      omri_saadon

                                      6,65531444




                                      6,65531444






















                                          up vote
                                          2
                                          down vote













                                          Here's a low tech solution without regex. :)



                                          >>> s = 'X did something. X found it to be good, and so X went home'
                                          >>> s = s.replace('X', 'Y').replace('Y', 'X', 1)
                                          >>> s
                                          >>> 'X did something. Y found it to be good, and so Y went home'


                                          Solution if 'Y' can exist in the original string:



                                          def replace_tail(s, target, replacement):
                                          try:
                                          pos = s.index(target)
                                          except ValueError:
                                          return s
                                          pos += len(target)
                                          head = s[:pos]
                                          tail = s[pos:]
                                          return head + tail.replace(target, replacement)


                                          Demo:



                                          >>> s = 'Today YYY and XXX did something. XXX found it to be good, and so XXX went home without YYY.'
                                          >>> replace_tail(s, 'XXX', 'YYY')
                                          >>> 'Today YYY and XXX did something. YYY found it to be good, and so YYY went home without YYY.'





                                          share|improve this answer



















                                          • 2




                                            Gonna run in to trouble if a Y already existed before the X.
                                            – Ry-
                                            Nov 10 at 14:33










                                          • @Ry- correct! Amit, can you clarify if this can happen? I might have to increase the tech level a bit.
                                            – timgeb
                                            Nov 10 at 14:35






                                          • 1




                                            Nice catch, In my use case, this can never happen. I like all of the proposed solutions, but this one is most elegant.
                                            – Amit
                                            Nov 10 at 14:38










                                          • @Amit in any case, I added a function that works in both scenarios.
                                            – timgeb
                                            Nov 10 at 14:47















                                          up vote
                                          2
                                          down vote













                                          Here's a low tech solution without regex. :)



                                          >>> s = 'X did something. X found it to be good, and so X went home'
                                          >>> s = s.replace('X', 'Y').replace('Y', 'X', 1)
                                          >>> s
                                          >>> 'X did something. Y found it to be good, and so Y went home'


                                          Solution if 'Y' can exist in the original string:



                                          def replace_tail(s, target, replacement):
                                          try:
                                          pos = s.index(target)
                                          except ValueError:
                                          return s
                                          pos += len(target)
                                          head = s[:pos]
                                          tail = s[pos:]
                                          return head + tail.replace(target, replacement)


                                          Demo:



                                          >>> s = 'Today YYY and XXX did something. XXX found it to be good, and so XXX went home without YYY.'
                                          >>> replace_tail(s, 'XXX', 'YYY')
                                          >>> 'Today YYY and XXX did something. YYY found it to be good, and so YYY went home without YYY.'





                                          share|improve this answer



















                                          • 2




                                            Gonna run in to trouble if a Y already existed before the X.
                                            – Ry-
                                            Nov 10 at 14:33










                                          • @Ry- correct! Amit, can you clarify if this can happen? I might have to increase the tech level a bit.
                                            – timgeb
                                            Nov 10 at 14:35






                                          • 1




                                            Nice catch, In my use case, this can never happen. I like all of the proposed solutions, but this one is most elegant.
                                            – Amit
                                            Nov 10 at 14:38










                                          • @Amit in any case, I added a function that works in both scenarios.
                                            – timgeb
                                            Nov 10 at 14:47













                                          up vote
                                          2
                                          down vote










                                          up vote
                                          2
                                          down vote









                                          Here's a low tech solution without regex. :)



                                          >>> s = 'X did something. X found it to be good, and so X went home'
                                          >>> s = s.replace('X', 'Y').replace('Y', 'X', 1)
                                          >>> s
                                          >>> 'X did something. Y found it to be good, and so Y went home'


                                          Solution if 'Y' can exist in the original string:



                                          def replace_tail(s, target, replacement):
                                          try:
                                          pos = s.index(target)
                                          except ValueError:
                                          return s
                                          pos += len(target)
                                          head = s[:pos]
                                          tail = s[pos:]
                                          return head + tail.replace(target, replacement)


                                          Demo:



                                          >>> s = 'Today YYY and XXX did something. XXX found it to be good, and so XXX went home without YYY.'
                                          >>> replace_tail(s, 'XXX', 'YYY')
                                          >>> 'Today YYY and XXX did something. YYY found it to be good, and so YYY went home without YYY.'





                                          share|improve this answer














                                          Here's a low tech solution without regex. :)



                                          >>> s = 'X did something. X found it to be good, and so X went home'
                                          >>> s = s.replace('X', 'Y').replace('Y', 'X', 1)
                                          >>> s
                                          >>> 'X did something. Y found it to be good, and so Y went home'


                                          Solution if 'Y' can exist in the original string:



                                          def replace_tail(s, target, replacement):
                                          try:
                                          pos = s.index(target)
                                          except ValueError:
                                          return s
                                          pos += len(target)
                                          head = s[:pos]
                                          tail = s[pos:]
                                          return head + tail.replace(target, replacement)


                                          Demo:



                                          >>> s = 'Today YYY and XXX did something. XXX found it to be good, and so XXX went home without YYY.'
                                          >>> replace_tail(s, 'XXX', 'YYY')
                                          >>> 'Today YYY and XXX did something. YYY found it to be good, and so YYY went home without YYY.'






                                          share|improve this answer














                                          share|improve this answer



                                          share|improve this answer








                                          edited Nov 10 at 14:42

























                                          answered Nov 10 at 14:32









                                          timgeb

                                          43.3k106084




                                          43.3k106084








                                          • 2




                                            Gonna run in to trouble if a Y already existed before the X.
                                            – Ry-
                                            Nov 10 at 14:33










                                          • @Ry- correct! Amit, can you clarify if this can happen? I might have to increase the tech level a bit.
                                            – timgeb
                                            Nov 10 at 14:35






                                          • 1




                                            Nice catch, In my use case, this can never happen. I like all of the proposed solutions, but this one is most elegant.
                                            – Amit
                                            Nov 10 at 14:38










                                          • @Amit in any case, I added a function that works in both scenarios.
                                            – timgeb
                                            Nov 10 at 14:47














                                          • 2




                                            Gonna run in to trouble if a Y already existed before the X.
                                            – Ry-
                                            Nov 10 at 14:33










                                          • @Ry- correct! Amit, can you clarify if this can happen? I might have to increase the tech level a bit.
                                            – timgeb
                                            Nov 10 at 14:35






                                          • 1




                                            Nice catch, In my use case, this can never happen. I like all of the proposed solutions, but this one is most elegant.
                                            – Amit
                                            Nov 10 at 14:38










                                          • @Amit in any case, I added a function that works in both scenarios.
                                            – timgeb
                                            Nov 10 at 14:47








                                          2




                                          2




                                          Gonna run in to trouble if a Y already existed before the X.
                                          – Ry-
                                          Nov 10 at 14:33




                                          Gonna run in to trouble if a Y already existed before the X.
                                          – Ry-
                                          Nov 10 at 14:33












                                          @Ry- correct! Amit, can you clarify if this can happen? I might have to increase the tech level a bit.
                                          – timgeb
                                          Nov 10 at 14:35




                                          @Ry- correct! Amit, can you clarify if this can happen? I might have to increase the tech level a bit.
                                          – timgeb
                                          Nov 10 at 14:35




                                          1




                                          1




                                          Nice catch, In my use case, this can never happen. I like all of the proposed solutions, but this one is most elegant.
                                          – Amit
                                          Nov 10 at 14:38




                                          Nice catch, In my use case, this can never happen. I like all of the proposed solutions, but this one is most elegant.
                                          – Amit
                                          Nov 10 at 14:38












                                          @Amit in any case, I added a function that works in both scenarios.
                                          – timgeb
                                          Nov 10 at 14:47




                                          @Amit in any case, I added a function that works in both scenarios.
                                          – timgeb
                                          Nov 10 at 14:47










                                          up vote
                                          1
                                          down vote













                                          Apply iteratively the regex after finding the first match over the remaining of the string. Or just using replace if it is possible.






                                          share|improve this answer

























                                            up vote
                                            1
                                            down vote













                                            Apply iteratively the regex after finding the first match over the remaining of the string. Or just using replace if it is possible.






                                            share|improve this answer























                                              up vote
                                              1
                                              down vote










                                              up vote
                                              1
                                              down vote









                                              Apply iteratively the regex after finding the first match over the remaining of the string. Or just using replace if it is possible.






                                              share|improve this answer












                                              Apply iteratively the regex after finding the first match over the remaining of the string. Or just using replace if it is possible.







                                              share|improve this answer












                                              share|improve this answer



                                              share|improve this answer










                                              answered Nov 10 at 14:32









                                              OmG

                                              7,28252643




                                              7,28252643






















                                                  up vote
                                                  1
                                                  down vote













                                                  We can use slicing to produce two string: first one up to (and including) the first element, and the next slice that contains the rest. We can then apply the replace part on that part, and merge these back:



                                                  def replace_but_first(text, search, replace):
                                                  try:
                                                  idx = text.index(search) + len(search)
                                                  return text[:idx] + text[idx:].replace(search, replace)
                                                  except ValueError: # we did not found a single match
                                                  return text


                                                  For example:



                                                  >>> replace_but_first('X did something. X found it to be good, and so X went home.', 'X', 'Y')
                                                  'X did something. Y found it to be good, and so Y went home.'





                                                  share|improve this answer























                                                  • @Ry-: sorry I was confused between index and find.
                                                    – Willem Van Onsem
                                                    Nov 10 at 14:40










                                                  • .find() strilcty speaking will work as well, although this is a bit ugly, and we save some cycles by not doing a second iteration over the string.
                                                    – Willem Van Onsem
                                                    Nov 10 at 14:41















                                                  up vote
                                                  1
                                                  down vote













                                                  We can use slicing to produce two string: first one up to (and including) the first element, and the next slice that contains the rest. We can then apply the replace part on that part, and merge these back:



                                                  def replace_but_first(text, search, replace):
                                                  try:
                                                  idx = text.index(search) + len(search)
                                                  return text[:idx] + text[idx:].replace(search, replace)
                                                  except ValueError: # we did not found a single match
                                                  return text


                                                  For example:



                                                  >>> replace_but_first('X did something. X found it to be good, and so X went home.', 'X', 'Y')
                                                  'X did something. Y found it to be good, and so Y went home.'





                                                  share|improve this answer























                                                  • @Ry-: sorry I was confused between index and find.
                                                    – Willem Van Onsem
                                                    Nov 10 at 14:40










                                                  • .find() strilcty speaking will work as well, although this is a bit ugly, and we save some cycles by not doing a second iteration over the string.
                                                    – Willem Van Onsem
                                                    Nov 10 at 14:41













                                                  up vote
                                                  1
                                                  down vote










                                                  up vote
                                                  1
                                                  down vote









                                                  We can use slicing to produce two string: first one up to (and including) the first element, and the next slice that contains the rest. We can then apply the replace part on that part, and merge these back:



                                                  def replace_but_first(text, search, replace):
                                                  try:
                                                  idx = text.index(search) + len(search)
                                                  return text[:idx] + text[idx:].replace(search, replace)
                                                  except ValueError: # we did not found a single match
                                                  return text


                                                  For example:



                                                  >>> replace_but_first('X did something. X found it to be good, and so X went home.', 'X', 'Y')
                                                  'X did something. Y found it to be good, and so Y went home.'





                                                  share|improve this answer














                                                  We can use slicing to produce two string: first one up to (and including) the first element, and the next slice that contains the rest. We can then apply the replace part on that part, and merge these back:



                                                  def replace_but_first(text, search, replace):
                                                  try:
                                                  idx = text.index(search) + len(search)
                                                  return text[:idx] + text[idx:].replace(search, replace)
                                                  except ValueError: # we did not found a single match
                                                  return text


                                                  For example:



                                                  >>> replace_but_first('X did something. X found it to be good, and so X went home.', 'X', 'Y')
                                                  'X did something. Y found it to be good, and so Y went home.'






                                                  share|improve this answer














                                                  share|improve this answer



                                                  share|improve this answer








                                                  edited Nov 10 at 14:40

























                                                  answered Nov 10 at 14:38









                                                  Willem Van Onsem

                                                  139k16131221




                                                  139k16131221












                                                  • @Ry-: sorry I was confused between index and find.
                                                    – Willem Van Onsem
                                                    Nov 10 at 14:40










                                                  • .find() strilcty speaking will work as well, although this is a bit ugly, and we save some cycles by not doing a second iteration over the string.
                                                    – Willem Van Onsem
                                                    Nov 10 at 14:41


















                                                  • @Ry-: sorry I was confused between index and find.
                                                    – Willem Van Onsem
                                                    Nov 10 at 14:40










                                                  • .find() strilcty speaking will work as well, although this is a bit ugly, and we save some cycles by not doing a second iteration over the string.
                                                    – Willem Van Onsem
                                                    Nov 10 at 14:41
















                                                  @Ry-: sorry I was confused between index and find.
                                                  – Willem Van Onsem
                                                  Nov 10 at 14:40




                                                  @Ry-: sorry I was confused between index and find.
                                                  – Willem Van Onsem
                                                  Nov 10 at 14:40












                                                  .find() strilcty speaking will work as well, although this is a bit ugly, and we save some cycles by not doing a second iteration over the string.
                                                  – Willem Van Onsem
                                                  Nov 10 at 14:41




                                                  .find() strilcty speaking will work as well, although this is a bit ugly, and we save some cycles by not doing a second iteration over the string.
                                                  – Willem Van Onsem
                                                  Nov 10 at 14:41


















                                                   

                                                  draft saved


                                                  draft discarded



















































                                                   


                                                  draft saved


                                                  draft discarded














                                                  StackExchange.ready(
                                                  function () {
                                                  StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53239936%2freplace-all-occurrences-in-string-but-the-first-one%23new-answer', 'question_page');
                                                  }
                                                  );

                                                  Post as a guest




















































































                                                  Popular posts from this blog

                                                  Bressuire

                                                  Vorschmack

                                                  Quarantine