在Python中按空格拆分字符串,保留引号内的子串
我有一个这样的字符串:
this is "a test"
我想用Python写个程序,把这个字符串按空格分开,但要忽略引号里面的空格。最终我想要的结果是:
['this', 'is', 'a test']
顺便说一下,我知道你们可能会问“如果引号里面还有引号怎么办?”在我的应用场景中,这种情况是不会发生的。
16 个回答
48
我看到这里有一些正则表达式的方法,看起来既复杂又可能不太对。这让我感到惊讶,因为正则表达式的语法其实很简单,可以轻松描述“空格或者被引号包围的东西”,而且大多数正则表达式引擎(包括Python的)都可以根据正则表达式进行分割。那么如果你打算使用正则表达式,为什么不直接说清楚你想要的呢?
test = 'this is "a test"' # or "this is 'a test'"
# pieces = [p for p in re.split("( |[\\\"'].*[\\\"'])", test) if p.strip()]
# From comments, use this:
pieces = [p for p in re.split("( |\\\".*?\\\"|'.*?')", test) if p.strip()]
解释:
[\\\"'] = double-quote or single-quote
.* = anything
( |X) = space or X
.strip() = remove space and empty-string separators
不过,shlex可能提供了更多的功能。
76
看看这个叫做 shlex
的模块,特别是里面的 shlex.split
这个功能。
>>> import shlex
>>> shlex.split('This is "a test"')
['This', 'is', 'a test']
530
你需要用到 split
,这个是内置的 shlex
模块里的功能。
>>> import shlex
>>> shlex.split('this is "a test"')
['this', 'is', 'a test']
这个方法应该能完全满足你的需求。
如果你想保留引号的话,可以传递 posix=False
这个参数。
>>> shlex.split('this is "a test"', posix=False)
['this', 'is', '"a test"']