如何将字符串拆分为列表? [英] How do I split a string into a list?
本文介绍了如何将字符串拆分为列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果我有这个字符串:
2 + 24 * 48/32
2+24*48/32
什么是创建此列表的最有效方法:
what is the most efficient approach for creating this list:
['2','+','24','*','48','/','32']
['2', '+', '24', '*', '48', '/', '32']
推荐答案
碰巧您要拆分的令牌已经是Python令牌,因此您可以使用内置的tokenize
模块.几乎是单线的:
It just so happens that the tokens you want split are already Python tokens, so you can use the built-in tokenize
module. It's almost a one-liner:
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']
这篇关于如何将字符串拆分为列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文