Python拆分字符串而不拆分转义字符 [英] Python split string without splitting escaped character

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

问题描述

有没有办法在不拆分转义字符的情况下拆分字符串?例如,我有一个字符串,想按 ':' 而不是按 '\:'

Is there a way to split a string without splitting escaped character? For example, I have a string and want to split by ':' and not by '\:'

http\://www.example.url:ftp\://www.example.url

结果应该如下:

['http\://www.example.url' , 'ftp\://www.example.url']

推荐答案

注意 : 似乎不是需要转义的字符.

Note that : doesn't appear to be a character that needs escaping.

我能想到的最简单的方法是在字符上拆分,然后在转义时将其添加回来.

The simplest way that I can think of to accomplish this is to split on the character, and then add it back in when it is escaped.

示例代码(非常需要一些整理.):

Sample code (In much need of some neatening.):

def splitNoEscapes(string, char):
    sections = string.split(char)
    sections = [i + (char if i[-1] == "\\" else "") for i in sections]
    result = ["" for i in sections]
    j = 0
    for s in sections:
        result[j] += s
        j += (1 if s[-1] != char else 0)
    return [i for i in result if i != ""]

这篇关于Python拆分字符串而不拆分转义字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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