How do I slice a string by characters in Python? [duplicate]












9
















This question already has an answer here:




  • Python - Find sequence of same characters

    3 answers



  • Splitting a string with repeated characters into a list using regex

    3 answers




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 do I make this in Python?










share|improve this question















marked as duplicate by Kasrâmvd python
Users with the  python badge can single-handedly close python questions as duplicates and reopen them as needed.

StackExchange.ready(function() {
if (StackExchange.options.isMobile) return;

$('.dupe-hammer-message-hover:not(.hover-bound)').each(function() {
var $hover = $(this).addClass('hover-bound'),
$msg = $hover.siblings('.dupe-hammer-message');

$hover.hover(
function() {
$hover.showInfoMessage('', {
messageElement: $msg.clone().show(),
transient: false,
position: { my: 'bottom left', at: 'top center', offsetTop: -7 },
dismissable: false,
relativeToBody: true
});
},
function() {
StackExchange.helpers.removeMessages();
}
);
});
});
yesterday


This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new 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
    yesterday
















9
















This question already has an answer here:




  • Python - Find sequence of same characters

    3 answers



  • Splitting a string with repeated characters into a list using regex

    3 answers




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 do I make this in Python?










share|improve this question















marked as duplicate by Kasrâmvd python
Users with the  python badge can single-handedly close python questions as duplicates and reopen them as needed.

StackExchange.ready(function() {
if (StackExchange.options.isMobile) return;

$('.dupe-hammer-message-hover:not(.hover-bound)').each(function() {
var $hover = $(this).addClass('hover-bound'),
$msg = $hover.siblings('.dupe-hammer-message');

$hover.hover(
function() {
$hover.showInfoMessage('', {
messageElement: $msg.clone().show(),
transient: false,
position: { my: 'bottom left', at: 'top center', offsetTop: -7 },
dismissable: false,
relativeToBody: true
});
},
function() {
StackExchange.helpers.removeMessages();
}
);
});
});
yesterday


This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new 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
    yesterday














9












9








9


3







This question already has an answer here:




  • Python - Find sequence of same characters

    3 answers



  • Splitting a string with repeated characters into a list using regex

    3 answers




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 do I make this in Python?










share|improve this question

















This question already has an answer here:




  • Python - Find sequence of same characters

    3 answers



  • Splitting a string with repeated characters into a list using regex

    3 answers




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 do I make this in Python?





This question already has an answer here:




  • Python - Find sequence of same characters

    3 answers



  • Splitting a string with repeated characters into a list using regex

    3 answers








python






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited yesterday









Peter Mortensen

13.8k1987113




13.8k1987113










asked yesterday









Hank ChowHank Chow

571




571




marked as duplicate by Kasrâmvd python
Users with the  python badge can single-handedly close python questions as duplicates and reopen them as needed.

StackExchange.ready(function() {
if (StackExchange.options.isMobile) return;

$('.dupe-hammer-message-hover:not(.hover-bound)').each(function() {
var $hover = $(this).addClass('hover-bound'),
$msg = $hover.siblings('.dupe-hammer-message');

$hover.hover(
function() {
$hover.showInfoMessage('', {
messageElement: $msg.clone().show(),
transient: false,
position: { my: 'bottom left', at: 'top center', offsetTop: -7 },
dismissable: false,
relativeToBody: true
});
},
function() {
StackExchange.helpers.removeMessages();
}
);
});
});
yesterday


This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.









marked as duplicate by Kasrâmvd python
Users with the  python badge can single-handedly close python questions as duplicates and reopen them as needed.

StackExchange.ready(function() {
if (StackExchange.options.isMobile) return;

$('.dupe-hammer-message-hover:not(.hover-bound)').each(function() {
var $hover = $(this).addClass('hover-bound'),
$msg = $hover.siblings('.dupe-hammer-message');

$hover.hover(
function() {
$hover.showInfoMessage('', {
messageElement: $msg.clone().show(),
transient: false,
position: { my: 'bottom left', at: 'top center', offsetTop: -7 },
dismissable: false,
relativeToBody: true
});
},
function() {
StackExchange.helpers.removeMessages();
}
);
});
});
yesterday


This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new 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
    yesterday














  • 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
    yesterday








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
yesterday





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
yesterday












5 Answers
5






active

oldest

votes


















15














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































      2














      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.




























        2














        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



















        • 5





          Wow...this is as unreadable as it could get...

          – heemayl
          yesterday



















        1














        t=input()
        c=[t[0]]
        for i in range(1,len(t)):
        if t[i]==c[-1][0]:
        c[-1]=c[-1]+t[i]
        else:
        c.append(t[i])
        print(c)





        share|improve this answer








        New contributor




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





















        • Please add some text to make the answer more descriptive.

          – v.coder
          yesterday


















        5 Answers
        5






        active

        oldest

        votes








        5 Answers
        5






        active

        oldest

        votes









        active

        oldest

        votes






        active

        oldest

        votes









        15














        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






























          15














          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




























            15












            15








            15







            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 yesterday









            Aran-Fey

            20.1k53671




            20.1k53671










            answered yesterday









            AustinAustin

            12.3k3930




            12.3k3930

























                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 yesterday









                    denis_lordenis_lor

                    1,45611130




                    1,45611130























                        2














                        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.

























                          2














                          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.























                            2












                            2








                            2







                            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 yesterday









                            TojrahTojrah

                            461




                            461




                            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.























                                2














                                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



















                                • 5





                                  Wow...this is as unreadable as it could get...

                                  – heemayl
                                  yesterday
















                                2














                                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



















                                • 5





                                  Wow...this is as unreadable as it could get...

                                  – heemayl
                                  yesterday














                                2












                                2








                                2







                                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 yesterday









                                quantummindquantummind

                                1,3541817




                                1,3541817








                                • 5





                                  Wow...this is as unreadable as it could get...

                                  – heemayl
                                  yesterday














                                • 5





                                  Wow...this is as unreadable as it could get...

                                  – heemayl
                                  yesterday








                                5




                                5





                                Wow...this is as unreadable as it could get...

                                – heemayl
                                yesterday





                                Wow...this is as unreadable as it could get...

                                – heemayl
                                yesterday











                                1














                                t=input()
                                c=[t[0]]
                                for i in range(1,len(t)):
                                if t[i]==c[-1][0]:
                                c[-1]=c[-1]+t[i]
                                else:
                                c.append(t[i])
                                print(c)





                                share|improve this answer








                                New contributor




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





















                                • Please add some text to make the answer more descriptive.

                                  – v.coder
                                  yesterday
















                                1














                                t=input()
                                c=[t[0]]
                                for i in range(1,len(t)):
                                if t[i]==c[-1][0]:
                                c[-1]=c[-1]+t[i]
                                else:
                                c.append(t[i])
                                print(c)





                                share|improve this answer








                                New contributor




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





















                                • Please add some text to make the answer more descriptive.

                                  – v.coder
                                  yesterday














                                1












                                1








                                1







                                t=input()
                                c=[t[0]]
                                for i in range(1,len(t)):
                                if t[i]==c[-1][0]:
                                c[-1]=c[-1]+t[i]
                                else:
                                c.append(t[i])
                                print(c)





                                share|improve this answer








                                New contributor




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










                                t=input()
                                c=[t[0]]
                                for i in range(1,len(t)):
                                if t[i]==c[-1][0]:
                                c[-1]=c[-1]+t[i]
                                else:
                                c.append(t[i])
                                print(c)






                                share|improve this answer








                                New contributor




                                Mr.A 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




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









                                answered yesterday









                                Mr.AMr.A

                                112




                                112




                                New contributor




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





                                New contributor





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






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













                                • Please add some text to make the answer more descriptive.

                                  – v.coder
                                  yesterday



















                                • Please add some text to make the answer more descriptive.

                                  – v.coder
                                  yesterday

















                                Please add some text to make the answer more descriptive.

                                – v.coder
                                yesterday





                                Please add some text to make the answer more descriptive.

                                – v.coder
                                yesterday



                                Popular posts from this blog

                                "Incorrect syntax near the keyword 'ON'. (on update cascade, on delete cascade,)

                                Alcedinidae

                                Origin of the phrase “under your belt”?