How do I coalesce a sequence of identical characters into just one?












7















Suppose I have this:



My---sun--is------very-big---.



I want to replace all multiple hyphens with just one hyphen.










share|improve this question




















  • 3





    Do you really want to coalesce only hyphens, or any run of duplicate characters?

    – Andrew Jaffe
    May 11 '10 at 19:35
















7















Suppose I have this:



My---sun--is------very-big---.



I want to replace all multiple hyphens with just one hyphen.










share|improve this question




















  • 3





    Do you really want to coalesce only hyphens, or any run of duplicate characters?

    – Andrew Jaffe
    May 11 '10 at 19:35














7












7








7


2






Suppose I have this:



My---sun--is------very-big---.



I want to replace all multiple hyphens with just one hyphen.










share|improve this question
















Suppose I have this:



My---sun--is------very-big---.



I want to replace all multiple hyphens with just one hyphen.







python regex string






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited May 12 '10 at 9:03









SilentGhost

194k47265263




194k47265263










asked May 11 '10 at 19:28









TIMEXTIMEX

68.7k274646953




68.7k274646953








  • 3





    Do you really want to coalesce only hyphens, or any run of duplicate characters?

    – Andrew Jaffe
    May 11 '10 at 19:35














  • 3





    Do you really want to coalesce only hyphens, or any run of duplicate characters?

    – Andrew Jaffe
    May 11 '10 at 19:35








3




3





Do you really want to coalesce only hyphens, or any run of duplicate characters?

– Andrew Jaffe
May 11 '10 at 19:35





Do you really want to coalesce only hyphens, or any run of duplicate characters?

– Andrew Jaffe
May 11 '10 at 19:35












10 Answers
10






active

oldest

votes


















16














import re

astr='My---sun--is------very-big---.'

print(re.sub('-+','-',astr))
# My-sun-is-very-big-.





share|improve this answer



















  • 1





    +1, but -{2,} would avoid replacing single - unnecessarily.

    – Tim Pietzcker
    May 12 '10 at 8:37



















13














If you want to replace any run of consecutive characters, you can use



>>> import re
>>> a = "AA---BC++++DDDD-EE$$$$FF"
>>> print(re.sub(r"(.)1+",r"1",a))
A-BC+D-E$F


If you only want to coalesce non-word-characters, use



>>> print(re.sub(r"(W)1+",r"1",a))
AA-BC+DDDD-EE$FF


If it's really just hyphens, I recommend unutbu's solution.






share|improve this answer

































    5














    If you really only want to coalesce hyphens, use the other suggestions. Otherwise you can write your own function, something like this:



    >>> def coalesce(x):
    ... n =
    ... for c in x:
    ... if not n or c != n[-1]:
    ... n.append(c)
    ... return ''.join(n)
    ...
    >>> coalesce('My---sun--is------very-big---.')
    'My-sun-is-very-big-.'
    >>> coalesce('aaabbbccc')
    'abc'





    share|improve this answer
























    • +1 for a general solution. Since the OP used English words in their example, specifying a set of characters to coalesce (or not coalesce) would probably be preferable so as to avoid mangling words with double letters (i.e. letters -> leters).

      – tgray
      May 11 '10 at 20:00











    • Agreed on the +1 for a general solution

      – mcpeterson
      May 11 '10 at 21:43



















    5














    As usual, there's a nice itertools solution, using groupby:



    >>> from itertools import groupby
    >>> s = 'aaaaa----bbb-----cccc----d-d-d'
    >>> ''.join(key for key, group in groupby(s))
    'a-b-c-d-d-d'





    share|improve this answer



















    • 1





      This solution doesn't answer the question if you only want to dedupe the hyphens. Is there an itertools solution that would keep 'aaaaa'?

      – mcpeterson
      May 11 '10 at 22:18








    • 2





      @McPeterson: Sure, but they're not as nice. For just handling hyphens, you can do ''.join(key if key == '-' else ''.join(group) for key, group in groupby(s)). For handling any non-alphanumeric character, ''.join(''.join(group) if key.isalnum() else key for key, group in groupby(s)). But I'd just use one of the regex solutions instead.

      – Will McCutchen
      May 11 '10 at 22:48



















    2














    How about:



    >>> import re
    >>> re.sub("-+", "-", "My---sun--is------very-big---.")
    'My-sun-is-very-big-.'


    the regular expression "-+" will look for 1 or more "-".






    share|improve this answer































      1














      re.sub('-+', '-', "My---sun--is------very-big---")





      share|improve this answer































        1














        How about an alternate without the re module:



        '-'.join(filter(lambda w: len(w) > 0, 'My---sun--is------very-big---.'.split("-")))


        Or going with Tim and FogleBird's previous suggestion, here's a more general method:



        def coalesce_factory(x):
        return lambda sent: x.join(filter(lambda w: len(w) > 0, sent.split(x)))

        hyphen_coalesce = coalesce_factory("-")
        hyphen_coalesce('My---sun--is------very-big---.')


        Though personally, I would use the re module first :)




        • mcpeterson






        share|improve this answer

































          0














          Another simple solution is the String object's replace function.



          while '--' in astr:
          astr = astr.replace('--','-')





          share|improve this answer































            0














            if you don't want to use regular expressions:



                my_string = my_string.split('-')
            my_string = filter(None, my_string)
            my_string = '-'.join(my_string)





            share|improve this answer































              0














              I have



              my_str = 'a, b,,,,, c, , , d'


              I want



              'a,b,c,d'


              compress all the blanks (the "replace" bit), then split on the comma, then if not None join with a comma in between:



              my_str_2 = ','.join([i for i in my_str.replace(" ", "").split(',') if i])





              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%2f2813829%2fhow-do-i-coalesce-a-sequence-of-identical-characters-into-just-one%23new-answer', 'question_page');
                }
                );

                Post as a guest















                Required, but never shown

























                10 Answers
                10






                active

                oldest

                votes








                10 Answers
                10






                active

                oldest

                votes









                active

                oldest

                votes






                active

                oldest

                votes









                16














                import re

                astr='My---sun--is------very-big---.'

                print(re.sub('-+','-',astr))
                # My-sun-is-very-big-.





                share|improve this answer



















                • 1





                  +1, but -{2,} would avoid replacing single - unnecessarily.

                  – Tim Pietzcker
                  May 12 '10 at 8:37
















                16














                import re

                astr='My---sun--is------very-big---.'

                print(re.sub('-+','-',astr))
                # My-sun-is-very-big-.





                share|improve this answer



















                • 1





                  +1, but -{2,} would avoid replacing single - unnecessarily.

                  – Tim Pietzcker
                  May 12 '10 at 8:37














                16












                16








                16







                import re

                astr='My---sun--is------very-big---.'

                print(re.sub('-+','-',astr))
                # My-sun-is-very-big-.





                share|improve this answer













                import re

                astr='My---sun--is------very-big---.'

                print(re.sub('-+','-',astr))
                # My-sun-is-very-big-.






                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered May 11 '10 at 19:31









                unutbuunutbu

                550k10111821239




                550k10111821239








                • 1





                  +1, but -{2,} would avoid replacing single - unnecessarily.

                  – Tim Pietzcker
                  May 12 '10 at 8:37














                • 1





                  +1, but -{2,} would avoid replacing single - unnecessarily.

                  – Tim Pietzcker
                  May 12 '10 at 8:37








                1




                1





                +1, but -{2,} would avoid replacing single - unnecessarily.

                – Tim Pietzcker
                May 12 '10 at 8:37





                +1, but -{2,} would avoid replacing single - unnecessarily.

                – Tim Pietzcker
                May 12 '10 at 8:37













                13














                If you want to replace any run of consecutive characters, you can use



                >>> import re
                >>> a = "AA---BC++++DDDD-EE$$$$FF"
                >>> print(re.sub(r"(.)1+",r"1",a))
                A-BC+D-E$F


                If you only want to coalesce non-word-characters, use



                >>> print(re.sub(r"(W)1+",r"1",a))
                AA-BC+DDDD-EE$FF


                If it's really just hyphens, I recommend unutbu's solution.






                share|improve this answer






























                  13














                  If you want to replace any run of consecutive characters, you can use



                  >>> import re
                  >>> a = "AA---BC++++DDDD-EE$$$$FF"
                  >>> print(re.sub(r"(.)1+",r"1",a))
                  A-BC+D-E$F


                  If you only want to coalesce non-word-characters, use



                  >>> print(re.sub(r"(W)1+",r"1",a))
                  AA-BC+DDDD-EE$FF


                  If it's really just hyphens, I recommend unutbu's solution.






                  share|improve this answer




























                    13












                    13








                    13







                    If you want to replace any run of consecutive characters, you can use



                    >>> import re
                    >>> a = "AA---BC++++DDDD-EE$$$$FF"
                    >>> print(re.sub(r"(.)1+",r"1",a))
                    A-BC+D-E$F


                    If you only want to coalesce non-word-characters, use



                    >>> print(re.sub(r"(W)1+",r"1",a))
                    AA-BC+DDDD-EE$FF


                    If it's really just hyphens, I recommend unutbu's solution.






                    share|improve this answer















                    If you want to replace any run of consecutive characters, you can use



                    >>> import re
                    >>> a = "AA---BC++++DDDD-EE$$$$FF"
                    >>> print(re.sub(r"(.)1+",r"1",a))
                    A-BC+D-E$F


                    If you only want to coalesce non-word-characters, use



                    >>> print(re.sub(r"(W)1+",r"1",a))
                    AA-BC+DDDD-EE$FF


                    If it's really just hyphens, I recommend unutbu's solution.







                    share|improve this answer














                    share|improve this answer



                    share|improve this answer








                    edited May 12 '10 at 8:39

























                    answered May 11 '10 at 20:10









                    Tim PietzckerTim Pietzcker

                    248k43374458




                    248k43374458























                        5














                        If you really only want to coalesce hyphens, use the other suggestions. Otherwise you can write your own function, something like this:



                        >>> def coalesce(x):
                        ... n =
                        ... for c in x:
                        ... if not n or c != n[-1]:
                        ... n.append(c)
                        ... return ''.join(n)
                        ...
                        >>> coalesce('My---sun--is------very-big---.')
                        'My-sun-is-very-big-.'
                        >>> coalesce('aaabbbccc')
                        'abc'





                        share|improve this answer
























                        • +1 for a general solution. Since the OP used English words in their example, specifying a set of characters to coalesce (or not coalesce) would probably be preferable so as to avoid mangling words with double letters (i.e. letters -> leters).

                          – tgray
                          May 11 '10 at 20:00











                        • Agreed on the +1 for a general solution

                          – mcpeterson
                          May 11 '10 at 21:43
















                        5














                        If you really only want to coalesce hyphens, use the other suggestions. Otherwise you can write your own function, something like this:



                        >>> def coalesce(x):
                        ... n =
                        ... for c in x:
                        ... if not n or c != n[-1]:
                        ... n.append(c)
                        ... return ''.join(n)
                        ...
                        >>> coalesce('My---sun--is------very-big---.')
                        'My-sun-is-very-big-.'
                        >>> coalesce('aaabbbccc')
                        'abc'





                        share|improve this answer
























                        • +1 for a general solution. Since the OP used English words in their example, specifying a set of characters to coalesce (or not coalesce) would probably be preferable so as to avoid mangling words with double letters (i.e. letters -> leters).

                          – tgray
                          May 11 '10 at 20:00











                        • Agreed on the +1 for a general solution

                          – mcpeterson
                          May 11 '10 at 21:43














                        5












                        5








                        5







                        If you really only want to coalesce hyphens, use the other suggestions. Otherwise you can write your own function, something like this:



                        >>> def coalesce(x):
                        ... n =
                        ... for c in x:
                        ... if not n or c != n[-1]:
                        ... n.append(c)
                        ... return ''.join(n)
                        ...
                        >>> coalesce('My---sun--is------very-big---.')
                        'My-sun-is-very-big-.'
                        >>> coalesce('aaabbbccc')
                        'abc'





                        share|improve this answer













                        If you really only want to coalesce hyphens, use the other suggestions. Otherwise you can write your own function, something like this:



                        >>> def coalesce(x):
                        ... n =
                        ... for c in x:
                        ... if not n or c != n[-1]:
                        ... n.append(c)
                        ... return ''.join(n)
                        ...
                        >>> coalesce('My---sun--is------very-big---.')
                        'My-sun-is-very-big-.'
                        >>> coalesce('aaabbbccc')
                        'abc'






                        share|improve this answer












                        share|improve this answer



                        share|improve this answer










                        answered May 11 '10 at 19:55









                        FogleBirdFogleBird

                        49k21103122




                        49k21103122













                        • +1 for a general solution. Since the OP used English words in their example, specifying a set of characters to coalesce (or not coalesce) would probably be preferable so as to avoid mangling words with double letters (i.e. letters -> leters).

                          – tgray
                          May 11 '10 at 20:00











                        • Agreed on the +1 for a general solution

                          – mcpeterson
                          May 11 '10 at 21:43



















                        • +1 for a general solution. Since the OP used English words in their example, specifying a set of characters to coalesce (or not coalesce) would probably be preferable so as to avoid mangling words with double letters (i.e. letters -> leters).

                          – tgray
                          May 11 '10 at 20:00











                        • Agreed on the +1 for a general solution

                          – mcpeterson
                          May 11 '10 at 21:43

















                        +1 for a general solution. Since the OP used English words in their example, specifying a set of characters to coalesce (or not coalesce) would probably be preferable so as to avoid mangling words with double letters (i.e. letters -> leters).

                        – tgray
                        May 11 '10 at 20:00





                        +1 for a general solution. Since the OP used English words in their example, specifying a set of characters to coalesce (or not coalesce) would probably be preferable so as to avoid mangling words with double letters (i.e. letters -> leters).

                        – tgray
                        May 11 '10 at 20:00













                        Agreed on the +1 for a general solution

                        – mcpeterson
                        May 11 '10 at 21:43





                        Agreed on the +1 for a general solution

                        – mcpeterson
                        May 11 '10 at 21:43











                        5














                        As usual, there's a nice itertools solution, using groupby:



                        >>> from itertools import groupby
                        >>> s = 'aaaaa----bbb-----cccc----d-d-d'
                        >>> ''.join(key for key, group in groupby(s))
                        'a-b-c-d-d-d'





                        share|improve this answer



















                        • 1





                          This solution doesn't answer the question if you only want to dedupe the hyphens. Is there an itertools solution that would keep 'aaaaa'?

                          – mcpeterson
                          May 11 '10 at 22:18








                        • 2





                          @McPeterson: Sure, but they're not as nice. For just handling hyphens, you can do ''.join(key if key == '-' else ''.join(group) for key, group in groupby(s)). For handling any non-alphanumeric character, ''.join(''.join(group) if key.isalnum() else key for key, group in groupby(s)). But I'd just use one of the regex solutions instead.

                          – Will McCutchen
                          May 11 '10 at 22:48
















                        5














                        As usual, there's a nice itertools solution, using groupby:



                        >>> from itertools import groupby
                        >>> s = 'aaaaa----bbb-----cccc----d-d-d'
                        >>> ''.join(key for key, group in groupby(s))
                        'a-b-c-d-d-d'





                        share|improve this answer



















                        • 1





                          This solution doesn't answer the question if you only want to dedupe the hyphens. Is there an itertools solution that would keep 'aaaaa'?

                          – mcpeterson
                          May 11 '10 at 22:18








                        • 2





                          @McPeterson: Sure, but they're not as nice. For just handling hyphens, you can do ''.join(key if key == '-' else ''.join(group) for key, group in groupby(s)). For handling any non-alphanumeric character, ''.join(''.join(group) if key.isalnum() else key for key, group in groupby(s)). But I'd just use one of the regex solutions instead.

                          – Will McCutchen
                          May 11 '10 at 22:48














                        5












                        5








                        5







                        As usual, there's a nice itertools solution, using groupby:



                        >>> from itertools import groupby
                        >>> s = 'aaaaa----bbb-----cccc----d-d-d'
                        >>> ''.join(key for key, group in groupby(s))
                        'a-b-c-d-d-d'





                        share|improve this answer













                        As usual, there's a nice itertools solution, using groupby:



                        >>> from itertools import groupby
                        >>> s = 'aaaaa----bbb-----cccc----d-d-d'
                        >>> ''.join(key for key, group in groupby(s))
                        'a-b-c-d-d-d'






                        share|improve this answer












                        share|improve this answer



                        share|improve this answer










                        answered May 11 '10 at 20:05









                        Will McCutchenWill McCutchen

                        11.4k33442




                        11.4k33442








                        • 1





                          This solution doesn't answer the question if you only want to dedupe the hyphens. Is there an itertools solution that would keep 'aaaaa'?

                          – mcpeterson
                          May 11 '10 at 22:18








                        • 2





                          @McPeterson: Sure, but they're not as nice. For just handling hyphens, you can do ''.join(key if key == '-' else ''.join(group) for key, group in groupby(s)). For handling any non-alphanumeric character, ''.join(''.join(group) if key.isalnum() else key for key, group in groupby(s)). But I'd just use one of the regex solutions instead.

                          – Will McCutchen
                          May 11 '10 at 22:48














                        • 1





                          This solution doesn't answer the question if you only want to dedupe the hyphens. Is there an itertools solution that would keep 'aaaaa'?

                          – mcpeterson
                          May 11 '10 at 22:18








                        • 2





                          @McPeterson: Sure, but they're not as nice. For just handling hyphens, you can do ''.join(key if key == '-' else ''.join(group) for key, group in groupby(s)). For handling any non-alphanumeric character, ''.join(''.join(group) if key.isalnum() else key for key, group in groupby(s)). But I'd just use one of the regex solutions instead.

                          – Will McCutchen
                          May 11 '10 at 22:48








                        1




                        1





                        This solution doesn't answer the question if you only want to dedupe the hyphens. Is there an itertools solution that would keep 'aaaaa'?

                        – mcpeterson
                        May 11 '10 at 22:18







                        This solution doesn't answer the question if you only want to dedupe the hyphens. Is there an itertools solution that would keep 'aaaaa'?

                        – mcpeterson
                        May 11 '10 at 22:18






                        2




                        2





                        @McPeterson: Sure, but they're not as nice. For just handling hyphens, you can do ''.join(key if key == '-' else ''.join(group) for key, group in groupby(s)). For handling any non-alphanumeric character, ''.join(''.join(group) if key.isalnum() else key for key, group in groupby(s)). But I'd just use one of the regex solutions instead.

                        – Will McCutchen
                        May 11 '10 at 22:48





                        @McPeterson: Sure, but they're not as nice. For just handling hyphens, you can do ''.join(key if key == '-' else ''.join(group) for key, group in groupby(s)). For handling any non-alphanumeric character, ''.join(''.join(group) if key.isalnum() else key for key, group in groupby(s)). But I'd just use one of the regex solutions instead.

                        – Will McCutchen
                        May 11 '10 at 22:48











                        2














                        How about:



                        >>> import re
                        >>> re.sub("-+", "-", "My---sun--is------very-big---.")
                        'My-sun-is-very-big-.'


                        the regular expression "-+" will look for 1 or more "-".






                        share|improve this answer




























                          2














                          How about:



                          >>> import re
                          >>> re.sub("-+", "-", "My---sun--is------very-big---.")
                          'My-sun-is-very-big-.'


                          the regular expression "-+" will look for 1 or more "-".






                          share|improve this answer


























                            2












                            2








                            2







                            How about:



                            >>> import re
                            >>> re.sub("-+", "-", "My---sun--is------very-big---.")
                            'My-sun-is-very-big-.'


                            the regular expression "-+" will look for 1 or more "-".






                            share|improve this answer













                            How about:



                            >>> import re
                            >>> re.sub("-+", "-", "My---sun--is------very-big---.")
                            'My-sun-is-very-big-.'


                            the regular expression "-+" will look for 1 or more "-".







                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered May 11 '10 at 19:34









                            Charles BeattieCharles Beattie

                            4,06012129




                            4,06012129























                                1














                                re.sub('-+', '-', "My---sun--is------very-big---")





                                share|improve this answer




























                                  1














                                  re.sub('-+', '-', "My---sun--is------very-big---")





                                  share|improve this answer


























                                    1












                                    1








                                    1







                                    re.sub('-+', '-', "My---sun--is------very-big---")





                                    share|improve this answer













                                    re.sub('-+', '-', "My---sun--is------very-big---")






                                    share|improve this answer












                                    share|improve this answer



                                    share|improve this answer










                                    answered May 11 '10 at 19:33









                                    Jakub HamplJakub Hampl

                                    32.2k86197




                                    32.2k86197























                                        1














                                        How about an alternate without the re module:



                                        '-'.join(filter(lambda w: len(w) > 0, 'My---sun--is------very-big---.'.split("-")))


                                        Or going with Tim and FogleBird's previous suggestion, here's a more general method:



                                        def coalesce_factory(x):
                                        return lambda sent: x.join(filter(lambda w: len(w) > 0, sent.split(x)))

                                        hyphen_coalesce = coalesce_factory("-")
                                        hyphen_coalesce('My---sun--is------very-big---.')


                                        Though personally, I would use the re module first :)




                                        • mcpeterson






                                        share|improve this answer






























                                          1














                                          How about an alternate without the re module:



                                          '-'.join(filter(lambda w: len(w) > 0, 'My---sun--is------very-big---.'.split("-")))


                                          Or going with Tim and FogleBird's previous suggestion, here's a more general method:



                                          def coalesce_factory(x):
                                          return lambda sent: x.join(filter(lambda w: len(w) > 0, sent.split(x)))

                                          hyphen_coalesce = coalesce_factory("-")
                                          hyphen_coalesce('My---sun--is------very-big---.')


                                          Though personally, I would use the re module first :)




                                          • mcpeterson






                                          share|improve this answer




























                                            1












                                            1








                                            1







                                            How about an alternate without the re module:



                                            '-'.join(filter(lambda w: len(w) > 0, 'My---sun--is------very-big---.'.split("-")))


                                            Or going with Tim and FogleBird's previous suggestion, here's a more general method:



                                            def coalesce_factory(x):
                                            return lambda sent: x.join(filter(lambda w: len(w) > 0, sent.split(x)))

                                            hyphen_coalesce = coalesce_factory("-")
                                            hyphen_coalesce('My---sun--is------very-big---.')


                                            Though personally, I would use the re module first :)




                                            • mcpeterson






                                            share|improve this answer















                                            How about an alternate without the re module:



                                            '-'.join(filter(lambda w: len(w) > 0, 'My---sun--is------very-big---.'.split("-")))


                                            Or going with Tim and FogleBird's previous suggestion, here's a more general method:



                                            def coalesce_factory(x):
                                            return lambda sent: x.join(filter(lambda w: len(w) > 0, sent.split(x)))

                                            hyphen_coalesce = coalesce_factory("-")
                                            hyphen_coalesce('My---sun--is------very-big---.')


                                            Though personally, I would use the re module first :)




                                            • mcpeterson







                                            share|improve this answer














                                            share|improve this answer



                                            share|improve this answer








                                            edited May 11 '10 at 21:47

























                                            answered May 11 '10 at 21:29









                                            mcpetersonmcpeterson

                                            3,22031621




                                            3,22031621























                                                0














                                                Another simple solution is the String object's replace function.



                                                while '--' in astr:
                                                astr = astr.replace('--','-')





                                                share|improve this answer




























                                                  0














                                                  Another simple solution is the String object's replace function.



                                                  while '--' in astr:
                                                  astr = astr.replace('--','-')





                                                  share|improve this answer


























                                                    0












                                                    0








                                                    0







                                                    Another simple solution is the String object's replace function.



                                                    while '--' in astr:
                                                    astr = astr.replace('--','-')





                                                    share|improve this answer













                                                    Another simple solution is the String object's replace function.



                                                    while '--' in astr:
                                                    astr = astr.replace('--','-')






                                                    share|improve this answer












                                                    share|improve this answer



                                                    share|improve this answer










                                                    answered May 11 '10 at 22:59









                                                    user334997user334997

                                                    11




                                                    11























                                                        0














                                                        if you don't want to use regular expressions:



                                                            my_string = my_string.split('-')
                                                        my_string = filter(None, my_string)
                                                        my_string = '-'.join(my_string)





                                                        share|improve this answer




























                                                          0














                                                          if you don't want to use regular expressions:



                                                              my_string = my_string.split('-')
                                                          my_string = filter(None, my_string)
                                                          my_string = '-'.join(my_string)





                                                          share|improve this answer


























                                                            0












                                                            0








                                                            0







                                                            if you don't want to use regular expressions:



                                                                my_string = my_string.split('-')
                                                            my_string = filter(None, my_string)
                                                            my_string = '-'.join(my_string)





                                                            share|improve this answer













                                                            if you don't want to use regular expressions:



                                                                my_string = my_string.split('-')
                                                            my_string = filter(None, my_string)
                                                            my_string = '-'.join(my_string)






                                                            share|improve this answer












                                                            share|improve this answer



                                                            share|improve this answer










                                                            answered Dec 8 '14 at 14:15







                                                            user4337613






























                                                                0














                                                                I have



                                                                my_str = 'a, b,,,,, c, , , d'


                                                                I want



                                                                'a,b,c,d'


                                                                compress all the blanks (the "replace" bit), then split on the comma, then if not None join with a comma in between:



                                                                my_str_2 = ','.join([i for i in my_str.replace(" ", "").split(',') if i])





                                                                share|improve this answer




























                                                                  0














                                                                  I have



                                                                  my_str = 'a, b,,,,, c, , , d'


                                                                  I want



                                                                  'a,b,c,d'


                                                                  compress all the blanks (the "replace" bit), then split on the comma, then if not None join with a comma in between:



                                                                  my_str_2 = ','.join([i for i in my_str.replace(" ", "").split(',') if i])





                                                                  share|improve this answer


























                                                                    0












                                                                    0








                                                                    0







                                                                    I have



                                                                    my_str = 'a, b,,,,, c, , , d'


                                                                    I want



                                                                    'a,b,c,d'


                                                                    compress all the blanks (the "replace" bit), then split on the comma, then if not None join with a comma in between:



                                                                    my_str_2 = ','.join([i for i in my_str.replace(" ", "").split(',') if i])





                                                                    share|improve this answer













                                                                    I have



                                                                    my_str = 'a, b,,,,, c, , , d'


                                                                    I want



                                                                    'a,b,c,d'


                                                                    compress all the blanks (the "replace" bit), then split on the comma, then if not None join with a comma in between:



                                                                    my_str_2 = ','.join([i for i in my_str.replace(" ", "").split(',') if i])






                                                                    share|improve this answer












                                                                    share|improve this answer



                                                                    share|improve this answer










                                                                    answered Jan 20 at 9:40









                                                                    MZAMZA

                                                                    32357




                                                                    32357






























                                                                        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%2f2813829%2fhow-do-i-coalesce-a-sequence-of-identical-characters-into-just-one%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

                                                                        Callistus III

                                                                        Plistias Cous

                                                                        Index Sanctorum