How do I slice a string by characters in Python? [duplicate]2019 Community Moderator ElectionSplitting a string with repeated characters into a list using regexPython - Find sequence of same charactersHow to separate a string of repeating characters?What are metaclasses in Python?Hidden features of PythonWhat does the “yield” keyword do?How do I parse a string to a float or int in Python?How to print without newline or space?How do I sort a dictionary by value?Getting the last element of a list in PythonHow to concatenate two lists in Python?How to read a file line-by-line into a list?Does Python have a string 'contains' substring method?

As a new Ubuntu desktop 18.04 LTS user, do I need to use ufw for a firewall or is iptables sufficient?

Why Choose Less Effective Armour Types?

Is it possible to upcast ritual spells?

Brexit - No Deal Rejection

What is a ^ b and (a & b) << 1?

What are substitutions for coconut in curry?

Is "upgrade" the right word to use in this context?

If I can solve Sudoku, can I solve the Travelling Salesman Problem (TSP)? If so, how?

What is the adequate fee for a reveal operation?

What is the Japanese sound word for the clinking of money?

Do I need life insurance if I can cover my own funeral costs?

Have the tides ever turned twice on any open problem?

Is there a place to find the pricing for things not mentioned in the PHB? (non-magical)

A diagram about partial derivatives of f(x,y)

I am confused as to how the inverse of a certain function is found.

This word with a lot of past tenses

PTIJ: Who should I vote for? (21st Knesset Edition)

Recruiter wants very extensive technical details about all of my previous work

Do I need to be arrogant to get ahead?

combinatorics floor summation

How are passwords stolen from companies if they only store hashes?

Is honey really a supersaturated solution? Does heating to un-crystalize redissolve it or melt it?

Professor being mistaken for a grad student

Math equation in non italic font



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



2019 Community Moderator ElectionSplitting a string with repeated characters into a list using regexPython - Find sequence of same charactersHow to separate a string of repeating characters?What are metaclasses in Python?Hidden features of PythonWhat does the “yield” keyword do?How do I parse a string to a float or int in Python?How to print without newline or space?How do I sort a dictionary by value?Getting the last element of a list in PythonHow to concatenate two lists in Python?How to read a file line-by-line into a list?Does Python have a string 'contains' substring method?










8
















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();

);
);
);
6 hours ago


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
    14 hours ago















8
















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();

);
);
);
6 hours ago


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
    14 hours ago













8












8








8


2







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 9 hours ago









Peter Mortensen

13.8k1986113




13.8k1986113










asked 14 hours ago









Hank ChowHank Chow

521




521




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();

);
);
);
6 hours ago


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();

);
);
);
6 hours ago


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
    14 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
    14 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
14 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
14 hours ago












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
          11 hours ago


















        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
          6 hours ago

















        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 14 hours ago









            Aran-Fey

            20.9k53671




            20.9k53671










            answered 14 hours ago









            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 14 hours ago









                    denis_lordenis_lor

                    1,37111130




                    1,37111130





















                        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 13 hours ago









                            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
                                  11 hours ago















                                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
                                  11 hours ago













                                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 12 hours ago









                                quantummindquantummind

                                1,3541817




                                1,3541817







                                • 5





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

                                  – heemayl
                                  11 hours ago












                                • 5





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

                                  – heemayl
                                  11 hours ago







                                5




                                5





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

                                – heemayl
                                11 hours ago





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

                                – heemayl
                                11 hours ago











                                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
                                  6 hours ago















                                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
                                  6 hours ago













                                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 7 hours ago









                                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
                                  6 hours ago

















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

                                  – v.coder
                                  6 hours ago
















                                Please add some text to make the answer more descriptive.

                                – v.coder
                                6 hours ago





                                Please add some text to make the answer more descriptive.

                                – v.coder
                                6 hours ago



                                Popular posts from this blog

                                Bett Inhaltsverzeichnis Geschichte | Bettformen | Bettgrößen | Andere Bezeichnungen | Bettenmangel | Betten in der bildenden Kunst | Schlafmedizinische Gesichtspunkte | Siehe auch | Literatur | Weblinks | Einzelnachweise | NavigationsmenüBett, Bettstatt, BettstelleCommons: BettBabybetten: Anwendung, Ausstattungsmerkmale und VergleichskriterienWasserbetten. Vorurteile im TestHapfnNursch10.1007/s11818-012-0584-74006250-8AKS4329276-8

                                Luksemburg Sisukord Nimi | Asend | Loodus | Riigikord | Haldusjaotus | Rahvastik | Riigikaitse | Majandus | Taristu | Ajalugu | Eesti ja Luksemburgi suhted | Haridus | Kultuur | Vaata ka | Viited | Välislingid | Navigeerimismenüü50° N, 6° EÜlevaade Luksemburgi kaitsealadest.Luksemburgi rahvaarv. Statistikaamet.World Bank'i andmebaasÜlevaade Luksemburgi loodusest.Ülevaade Luksemburgi metsadest.Guy Colling. "Red List of the Vascular Plants of Luxembourg." Travaux scientifiques du Musée national d’histoire naturelle Luxembourg. 2005.Luxembourg’s biodiversity at risk.Maailma kahepaiksete andmebaas.Denis Lepage. "Luxembourg." Avibase.Ülevaade temperatuuridest. Luksemburgi meteoroloogiateenistus.Ülevaade Luksemburgist. Euroopa Liidu esinduse koduleht.Système politique. TerritoireÜlevaade Luksemburgi rahvastikust. Luksemburgi statistikaamet.Luksemburgi rahvastik. Luksemburgi statistikaamet.The World FactbookMonique Borsenberger, Paul Dickes. "Religions au Luxembourg. Quelle évolution entre 1999-2008". Luksemburgi statistikaamet. 2011.Luksemburgi peapiiskopkond. Catholic-Hierarchy.Luksemburgi armee koduleht.Luksemburgi armee relvastus.Eesti Välisministeerium.Luksemburgi rahvastik. Luksemburgi statistikaamet.Luksemburgi Eesti Seltsi koduleht.Helen Eelrand. "Raadio, mis muutis maailma." Eesti Päevaleht. 13. märts 2004.Ülevaade Luksemburgi haridussüsteemist.Ülevaade Luksemburgi keskkoolidest.Luksemburgr

                                Valle di Casies Indice Geografia fisica | Origini del nome | Storia | Società | Amministrazione | Sport | Note | Bibliografia | Voci correlate | Altri progetti | Collegamenti esterni | Menu di navigazione46°46′N 12°11′E / 46.766667°N 12.183333°E46.766667; 12.183333 (Valle di Casies)46°46′N 12°11′E / 46.766667°N 12.183333°E46.766667; 12.183333 (Valle di Casies)Sito istituzionaleAstat Censimento della popolazione 2011 - Determinazione della consistenza dei tre gruppi linguistici della Provincia Autonoma di Bolzano-Alto Adige - giugno 2012Numeri e fattiValle di CasiesDato IstatTabella dei gradi/giorno dei Comuni italiani raggruppati per Regione e Provincia26 agosto 1993, n. 412Heraldry of the World: GsiesStatistiche I.StatValCasies.comWikimedia CommonsWikimedia CommonsValle di CasiesSito ufficialeValle di CasiesMM14870458910042978-6