在python中分割字符串 [英] Splitting strings in python

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

问题描述

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

I have a string which is like this:

这是[括号测试]和引号测试"

this is [bracket test] "and quotes test "

我试图用Python编写一些内容,以按空格将其拆分,同时忽略方括号和引号内的空格.我正在寻找的结果是:

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

['this','is','bracket test','and quotes test']

['this','is','bracket test','and quotes test ']

推荐答案

以下是可与您的测试输入配合使用的简单解决方案:

Here's a simplistic solution that works with your test input:

import re
re.findall('\[[^\]]*\]|\"[^\"]*\"|\S+',s)

这将返回与以下任何一个匹配的代码

This will return any code that matches either

  • 右方括号后接零个或多个非右方括号字符,后接右方括号
  • 双引号,后跟零个或多个非引号字符,后接引号,
  • 任何一组非空格字符

这适用于您的示例,但是对于您可能遇到的许多实际字符串而言可能会失败.例如,您没有说出用不平衡的括号或引号引起的期望,或者说单引号或转义字符如何工作.不过,对于简单的情况,上面的内容可能就足够了.

This works with your example, but might fail for many real-world strings you may encounter. For example, you didn't say what you expect with unbalanced brackets or quotes,or how you want single quotes or escape characters to work. For simple cases, though, the above might be good enough.

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

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