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.

有帮助吗?

解决方案

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.

其他提示

You could use a regular expression:

import re
cubedirs = re.compile(r"[RLFBUDrlfbudxyz][2']?")
cubedirs.findall("RL2R'F2LD'")

This outputs ['R', 'L2', "R'", 'F2', 'L', "D'"].

The regular expression is actually very simple. The [..] character group means: match one character from the set given (so an R, or an L, or an F, etc.).

Then we look for a second character group optionally matching 1 character, namely a 2 or '. The question mark after the second character is what makes it optional; we are specifying that it's also fine if the ' or the 2 character is not there.

The .findall() method simply returns all matches that have been found, so you get a list of all character groups in the input string that match the pattern.

You could use a regular expression:

[FBUDLRfbudlrxyz][2']?

Here's a live demo.

import re

s = "RL2R'F2LD'"

for m in re.finditer("[FBUDLRfbudlrxyz][2']?", s):
    print m.group(0)

(Sorry for not explaining how to do it in the comments, I don't really know Python.)

As commented, a regular expression would be a good way:

>>> import re
>>> re.findall('[A-Z]{1}[0-9]{0,1}', "RL2R'F2LD'")
['R', 'L2', 'R', 'F2', 'L', 'D']
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top