# 如何将一个string分割成一个列表？

2 + 24 *32分之48

['2'，'+'，'24'，'*'，'48'，'/'，'32']

` `from cStringIO import StringIO from tokenize import generate_tokens STRING = 1 list(token[STRING] for token in generate_tokens(StringIO('2+24*48/32').readline) if token[STRING]) ['2', '+', '24', '*', '48', '/', '32']` `

re.split（pattern，string，maxsplit = 0，flags = 0）

` `import re data = re.split(r'(\D)', '2+24*48/32')` `

\ d

` `import re patterns = [ ('number', re.compile('\d+')), ('*', re.compile(r'\*')), ('/', re.compile(r'\/')), ('+', re.compile(r'\+')), ('-', re.compile(r'\-')), ] whitespace = re.compile('\W+') def tokenize(string): while string: # strip off whitespace m = whitespace.match(string) if m: string = string[m.end():] for tokentype, pattern in patterns: m = pattern.match(string) if m: yield tokentype, m.group(0) string = string[m.end():] def parseNumber(tokens): tokentype, literal = tokens.pop(0) assert tokentype == 'number' return int(literal) def parseMultiplication(tokens): product = parseNumber(tokens) while tokens and tokens[0][0] in ('*', '/'): tokentype, literal = tokens.pop(0) if tokentype == '*': product *= parseNumber(tokens) elif tokentype == '/': product /= parseNumber(tokens) else: raise ValueError("Parse Error, unexpected %s %s" % (tokentype, literal)) return product def parseAddition(tokens): total = parseMultiplication(tokens) while tokens and tokens[0][0] in ('+', '-'): tokentype, literal = tokens.pop(0) if tokentype == '+': total += parseMultiplication(tokens) elif tokentype == '-': total -= parseMultiplication(tokens) else: raise ValueError("Parse Error, unexpected %s %s" % (tokentype, literal)) return total def parse(tokens): tokenlist = list(tokens) returnvalue = parseAddition(tokenlist) if tokenlist: print 'Unconsumed data', tokenlist return returnvalue def main(): string = '2+24*48/32' for tokentype, literal in tokenize(string): print tokentype, literal print parse(tokenize(string)) if __name__ == '__main__': main()` `

` `>>> import re >>> re.findall(r'\d+|\D+', '2+24*48/32=10') ['2', '+', '24', '*', '48', '/', '32', '=', '10']` `

` `>>> re.findall(r'[0-9\.]+|[^0-9\.]+', '2+24*48/32=10.1') ['2', '+', '24', '*', '48', '/', '32', '=', '10.1']` `

` `>>> import re >>> splitter = re.compile(r'([+*/])') >>> splitter.split("2+24*48/32")` `

s =“2 + 24 * 48/32”

p = re.compile（r'（\ W +）'）

p.split（S）

` `import operator, math calc_operands = { '+': (2, operator.add), '-': (2, operator.sub), '*': (2, operator.mul), '/': (2, operator.truediv), '//': (2, operator.div), '%': (2, operator.mod), '^': (2, operator.pow), '**': (2, math.pow), 'abs': (1, operator.abs), 'ceil': (1, math.ceil), 'floor': (1, math.floor), 'round': (2, round), 'trunc': (1, int), 'log': (2, math.log), 'ln': (1, math.log), 'pi': (0, lambda: math.pi), 'e': (0, lambda: math.e), } def calculate(inp): stack = [] for tok in inp.split(): if tok in self.calc_operands: n_pops, func = self.calc_operands[tok] args = [stack.pop() for x in xrange(n_pops)] args.reverse() stack.append(func(*args)) elif '.' in tok: stack.append(float(tok)) else: stack.append(int(tok)) if not stack: raise ValueError('no items on the stack.') return stack.pop() if stack: raise ValueError('%d item(s) left on the stack.' % len(stack)) calculate('24 38 * 32 / 2 +')` `
` `>>> import re >>> my_string = "2+24*48/32" >>> my_list = re.findall(r"-?\d+|\S", my_string) >>> print my_list ['2', '+', '24', '*', '48', '/', '32']` `

expression式=“2 + 24 * 48/32”
exec “result =”+expression式

38

` `splitter = re.compile(r'([\D])').` `