Search code examples
pythonstringsplitrubiks-cube

Most efficient way of splitting strings like rubik's cube notations in python?


If a string like "RL2R'F2LD'" given,What is the most efficient way of splitting this into Strings "R" "L2" "R'" "F2" "L" "D'"? I'v tried few methods like first splitting them into individual chars and then trying to add them to a list and nothing worked correctly.


Solution

  • def rubikstring(s):
        import string
        cumu = ''
        for c in s:
            if c in string.ascii_letters:
                if cumu: yield cumu
                cumu = ''
            cumu += c
        if cumu: yield cumu
    

    could do your job. With

    >>> for i in rubikstring("RL2R'F2LD'"): i
    ...
    'R'
    'L2'
    "R'"
    'F2'
    'L'
    "D'"
    

    you get your desired result, with

    >>> list(rubikstring("RL2R'F2LD'"))
    ['R', 'L2', "R'", 'F2', 'L', "D'"]
    

    as well.