忽略引号中的分割符

python中字符串的split能很方便的将字符串根据指定的分割符分割,但是如果不想分割引号中的分割符的话,split就无能为力了,写了一个小函数,忽略引号中的分割符


def my_split(s, sep=' ', ignore='"'):
    """以seq分割,重复的seq按一个计算,忽略ignore中的seq,返回开始、结束这样的索引数组"""
    ignore_flag = False  # 是否在ignore中
    sep_flag = True  # 上一个是否是
    indexs = []
    for index, i in enumerate(s):
        if i in ignore:
            ignore_flag = not ignore_flag
        elif i == sep:
            if not ignore_flag and not sep_flag:
                sep_flag = True
                indexs[-1].append(index - 1)  # 结束的索引
        else:
            if sep_flag:
                indexs.append([index])  # 开始的索引
            sep_flag = False
    if s[-1] != sep:  # 最后一个不是seq,将最后一个索引添加
        indexs[-1].append(len(s) - 1)
    return indexs

print my_split('afdsf="sdf   sfsd"  qwe="eqwe qwe "', ' ', '"')
返回[[0, 17], [20, 34]]


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值