首页 > 解决方案 > 拆分文本包含空格,但将引号内的单词作为一个单元

问题描述

我想将文本拆分为列表,其中带空格的文件名应视为单个项目:示例

s = 'cmd -a -b -c "file with spaces.mp4" -e -f'.split()
print(s)

输出:

['cmd', '-a', '-b', '-c', '"file', 'with', 'spaces.mp4"', '-e', '-f']

所需的输出:

['cmd', '-a', '-b', '-c', '"file with spaces.mp4"', '-e', '-f']

我尝试使用一些 for 循环,但它变得讨厌,有没有使用正则表达式或其他任何看起来不丑的体面的方法

标签: pythonregex

解决方案


实际上,在这种情况下,我不会使用正则表达式。这shlex.split()是为了:

import shlex

s = shlex.split( 'cmd -a -b -c "file with spaces.mp4" -e -f' )
print(s)

印刷:

['cmd', '-a', '-b', '-c', 'file with spaces.mp4', '-e', '-f']

推荐阅读