用空格分割字符串——保留引用的子字符串——在 Python 中 [英] Split a string by spaces -- preserving quoted substrings -- in Python

查看:58
本文介绍了用空格分割字符串——保留引用的子字符串——在 Python 中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像这样的字符串:

这是一个测试"

我正在尝试用 Python 编写一些东西,以将其按空格分开,同时忽略引号内的空格.我正在寻找的结果是:

['this','is','a test']

附注.我知道你会问如果引号中有引号会发生什么,嗯,在我的应用程序中,这永远不会发生.

解决方案

你想要 split,来自内置的 shlex 模块.

<预><代码>>>>进口shlex>>>shlex.split('这是测试"')['这是一个测试']

这应该完全符合您的要求.

I have a string which is like this:

this is "a test"

I'm trying to write something in Python to split it up by space while ignoring spaces within quotes. The result I'm looking for is:

['this','is','a test']

PS. I know you are going to ask "what happens if there are quotes within the quotes, well, in my application, that will never happen.

解决方案

You want split, from the built-in shlex module.

>>> import shlex
>>> shlex.split('this is "a test"')
['this', 'is', 'a test']

This should do exactly what you want.

这篇关于用空格分割字符串——保留引用的子字符串——在 Python 中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆