how to slice a string by characters in Python?












6















There is a string with one or more characters. I want to slice the list so that the adjoining same characters are in the same element. For example:



'a' -> ['a']
'abbbcc' -> ['a', 'bbb', 'cc']
'abcabc' -> ['a', 'b', 'c', 'a', 'b', 'c']


How to make this in Python?










share|improve this question


















  • 1





    FYI, if you google "python group identical elements" or something similar you'll find plenty of recipes that would help you get started.

    – Aran-Fey
    2 hours ago
















6















There is a string with one or more characters. I want to slice the list so that the adjoining same characters are in the same element. For example:



'a' -> ['a']
'abbbcc' -> ['a', 'bbb', 'cc']
'abcabc' -> ['a', 'b', 'c', 'a', 'b', 'c']


How to make this in Python?










share|improve this question


















  • 1





    FYI, if you google "python group identical elements" or something similar you'll find plenty of recipes that would help you get started.

    – Aran-Fey
    2 hours ago














6












6








6








There is a string with one or more characters. I want to slice the list so that the adjoining same characters are in the same element. For example:



'a' -> ['a']
'abbbcc' -> ['a', 'bbb', 'cc']
'abcabc' -> ['a', 'b', 'c', 'a', 'b', 'c']


How to make this in Python?










share|improve this question














There is a string with one or more characters. I want to slice the list so that the adjoining same characters are in the same element. For example:



'a' -> ['a']
'abbbcc' -> ['a', 'bbb', 'cc']
'abcabc' -> ['a', 'b', 'c', 'a', 'b', 'c']


How to make this in Python?







python






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked 2 hours ago









Hank ChowHank Chow

391




391








  • 1





    FYI, if you google "python group identical elements" or something similar you'll find plenty of recipes that would help you get started.

    – Aran-Fey
    2 hours ago














  • 1





    FYI, if you google "python group identical elements" or something similar you'll find plenty of recipes that would help you get started.

    – Aran-Fey
    2 hours ago








1




1





FYI, if you google "python group identical elements" or something similar you'll find plenty of recipes that would help you get started.

– Aran-Fey
2 hours ago





FYI, if you google "python group identical elements" or something similar you'll find plenty of recipes that would help you get started.

– Aran-Fey
2 hours ago












4 Answers
4






active

oldest

votes


















9














Use itertools.groupby:



from itertools import groupby

s = 'abccbba'

print([''.join(v) for _, v in groupby(s)])
# ['a', 'b', 'cc', 'bb', 'a']





share|improve this answer

































    4














    Can be achieved with re.finditer()



    import re
    s='aabccdd'
    print([m.group(0) for m in re.finditer(r"(w)1*", s)])
    #['aa', 'b', 'cc', 'dd']





    share|improve this answer































      0














      Without any modules and using for loop also it can be done in interesting way:



      l=
      str="aabccc"
      s=str[0]
      for c in str[1:]:

      if(c!=s[-1]):
      l.append(s)
      s=c
      else:
      s=s+c
      l.append(s)
      print(l)





      share|improve this answer








      New contributor




      Tojrah is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.




























        0














        Just one more alternative solution. You need no import for it in python2. In python3 you need import from functools.



        from functools import reduce   # in python3
        s='aaabccdddddaa'
        reduce(lambda x,y:x[:-1]+[x[-1]+y] if len(x)>0 and x[-1][-1]==y else x+[y], s, )





        share|improve this answer























          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',
          autoActivateHeartbeat: false,
          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%2f55194935%2fhow-to-slice-a-string-by-characters-in-python%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          4 Answers
          4






          active

          oldest

          votes








          4 Answers
          4






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          9














          Use itertools.groupby:



          from itertools import groupby

          s = 'abccbba'

          print([''.join(v) for _, v in groupby(s)])
          # ['a', 'b', 'cc', 'bb', 'a']





          share|improve this answer






























            9














            Use itertools.groupby:



            from itertools import groupby

            s = 'abccbba'

            print([''.join(v) for _, v in groupby(s)])
            # ['a', 'b', 'cc', 'bb', 'a']





            share|improve this answer




























              9












              9








              9







              Use itertools.groupby:



              from itertools import groupby

              s = 'abccbba'

              print([''.join(v) for _, v in groupby(s)])
              # ['a', 'b', 'cc', 'bb', 'a']





              share|improve this answer















              Use itertools.groupby:



              from itertools import groupby

              s = 'abccbba'

              print([''.join(v) for _, v in groupby(s)])
              # ['a', 'b', 'cc', 'bb', 'a']






              share|improve this answer














              share|improve this answer



              share|improve this answer








              edited 2 hours ago









              Aran-Fey

              20.8k53671




              20.8k53671










              answered 2 hours ago









              AustinAustin

              12.2k3929




              12.2k3929

























                  4














                  Can be achieved with re.finditer()



                  import re
                  s='aabccdd'
                  print([m.group(0) for m in re.finditer(r"(w)1*", s)])
                  #['aa', 'b', 'cc', 'dd']





                  share|improve this answer




























                    4














                    Can be achieved with re.finditer()



                    import re
                    s='aabccdd'
                    print([m.group(0) for m in re.finditer(r"(w)1*", s)])
                    #['aa', 'b', 'cc', 'dd']





                    share|improve this answer


























                      4












                      4








                      4







                      Can be achieved with re.finditer()



                      import re
                      s='aabccdd'
                      print([m.group(0) for m in re.finditer(r"(w)1*", s)])
                      #['aa', 'b', 'cc', 'dd']





                      share|improve this answer













                      Can be achieved with re.finditer()



                      import re
                      s='aabccdd'
                      print([m.group(0) for m in re.finditer(r"(w)1*", s)])
                      #['aa', 'b', 'cc', 'dd']






                      share|improve this answer












                      share|improve this answer



                      share|improve this answer










                      answered 2 hours ago









                      denis_lordenis_lor

                      1,36111030




                      1,36111030























                          0














                          Without any modules and using for loop also it can be done in interesting way:



                          l=
                          str="aabccc"
                          s=str[0]
                          for c in str[1:]:

                          if(c!=s[-1]):
                          l.append(s)
                          s=c
                          else:
                          s=s+c
                          l.append(s)
                          print(l)





                          share|improve this answer








                          New contributor




                          Tojrah is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                          Check out our Code of Conduct.

























                            0














                            Without any modules and using for loop also it can be done in interesting way:



                            l=
                            str="aabccc"
                            s=str[0]
                            for c in str[1:]:

                            if(c!=s[-1]):
                            l.append(s)
                            s=c
                            else:
                            s=s+c
                            l.append(s)
                            print(l)





                            share|improve this answer








                            New contributor




                            Tojrah is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                            Check out our Code of Conduct.























                              0












                              0








                              0







                              Without any modules and using for loop also it can be done in interesting way:



                              l=
                              str="aabccc"
                              s=str[0]
                              for c in str[1:]:

                              if(c!=s[-1]):
                              l.append(s)
                              s=c
                              else:
                              s=s+c
                              l.append(s)
                              print(l)





                              share|improve this answer








                              New contributor




                              Tojrah is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                              Check out our Code of Conduct.










                              Without any modules and using for loop also it can be done in interesting way:



                              l=
                              str="aabccc"
                              s=str[0]
                              for c in str[1:]:

                              if(c!=s[-1]):
                              l.append(s)
                              s=c
                              else:
                              s=s+c
                              l.append(s)
                              print(l)






                              share|improve this answer








                              New contributor




                              Tojrah is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                              Check out our Code of Conduct.









                              share|improve this answer



                              share|improve this answer






                              New contributor




                              Tojrah is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                              Check out our Code of Conduct.









                              answered 1 hour ago









                              TojrahTojrah

                              1




                              1




                              New contributor




                              Tojrah is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                              Check out our Code of Conduct.





                              New contributor





                              Tojrah is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                              Check out our Code of Conduct.






                              Tojrah is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                              Check out our Code of Conduct.























                                  0














                                  Just one more alternative solution. You need no import for it in python2. In python3 you need import from functools.



                                  from functools import reduce   # in python3
                                  s='aaabccdddddaa'
                                  reduce(lambda x,y:x[:-1]+[x[-1]+y] if len(x)>0 and x[-1][-1]==y else x+[y], s, )





                                  share|improve this answer




























                                    0














                                    Just one more alternative solution. You need no import for it in python2. In python3 you need import from functools.



                                    from functools import reduce   # in python3
                                    s='aaabccdddddaa'
                                    reduce(lambda x,y:x[:-1]+[x[-1]+y] if len(x)>0 and x[-1][-1]==y else x+[y], s, )





                                    share|improve this answer


























                                      0












                                      0








                                      0







                                      Just one more alternative solution. You need no import for it in python2. In python3 you need import from functools.



                                      from functools import reduce   # in python3
                                      s='aaabccdddddaa'
                                      reduce(lambda x,y:x[:-1]+[x[-1]+y] if len(x)>0 and x[-1][-1]==y else x+[y], s, )





                                      share|improve this answer













                                      Just one more alternative solution. You need no import for it in python2. In python3 you need import from functools.



                                      from functools import reduce   # in python3
                                      s='aaabccdddddaa'
                                      reduce(lambda x,y:x[:-1]+[x[-1]+y] if len(x)>0 and x[-1][-1]==y else x+[y], s, )






                                      share|improve this answer












                                      share|improve this answer



                                      share|improve this answer










                                      answered 37 mins ago









                                      quantummindquantummind

                                      1,3341817




                                      1,3341817






























                                          draft saved

                                          draft discarded




















































                                          Thanks for contributing an answer to Stack Overflow!


                                          • Please be sure to answer the question. Provide details and share your research!

                                          But avoid



                                          • Asking for help, clarification, or responding to other answers.

                                          • Making statements based on opinion; back them up with references or personal experience.


                                          To learn more, see our tips on writing great answers.




                                          draft saved


                                          draft discarded














                                          StackExchange.ready(
                                          function () {
                                          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55194935%2fhow-to-slice-a-string-by-characters-in-python%23new-answer', 'question_page');
                                          }
                                          );

                                          Post as a guest















                                          Required, but never shown





















































                                          Required, but never shown














                                          Required, but never shown












                                          Required, but never shown







                                          Required, but never shown

































                                          Required, but never shown














                                          Required, but never shown












                                          Required, but never shown







                                          Required, but never shown







                                          Popular posts from this blog

                                          Loup dans la culture

                                          How to solve the problem of ntp “Unable to contact time server” from KDE?

                                          ASUS Zenbook UX433/UX333 — Configure Touchpad-embedded numpad on Linux