python - 拆分文本包含空格,但将引号内的单词作为一个单元
问题描述
我想将文本拆分为列表,其中带空格的文件名应视为单个项目:示例
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 循环,但它变得讨厌,有没有使用正则表达式或其他任何看起来不丑的体面的方法
解决方案
实际上,在这种情况下,我不会使用正则表达式。这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']
推荐阅读
- r - 需要在 R 编程中使用正则表达式清理我的字符串
- linux - 源代码中的 SDL2 未找到任何视频驱动程序
- javascript - Angular 6 存储会话数据
- c# - 使用 Exchange Web 服务从 EmailMessage 中删除附件
- java - 春季批量重启作业从初始阶段开始,而不是从中断的地方开始?
- sql-server - 查询产生三个不同的结果集而不是一个
- jhipster - 如何在 jhipster 中正确保护我的休息端点?
- sql - 找到最大的唯一数据集。来自 3 列的值
- sql - 根据取自另一表的值更新一个表的日期字段
- mysql - MYSQL:我正在尝试设置触发器以在更新时更新我的当前行。(不更新所有行,只更新更新的行)