Split a string by backslash in python

后端 未结 5 1195
悲哀的现实
悲哀的现实 2020-12-06 09:41

Simple question but I\'m struggling with it for too much time. Basically I want to split a string by \\ (backslash).

 a = \"1\\2\\3\\4\"

Tr

5条回答
  •  离开以前
    2020-12-06 10:05

    Covering all the special cases like \a,\b, \f, \n, \r, \t, \v (String Literals)

    def split_str(str):
        ref_dict = {
            '\x07':'a',
            '\x08':'b',
            '\x0C':'f',
            '\n':'n',
            '\r':'r',
            '\t':'t',
            '\x0b':'v',                
        }    
        res_arr = []
        temp = ''
        for i in str :
            if not i == '\\':
                if i in ref_dict:
                    if not temp == "":
                        res_arr.append(temp)
                    res_arr.append(ref_dict[i])
                    temp = ''
                else:    
                    temp += i
            else:
                if not temp == '':
                    res_arr.append(temp)
                temp = ''
        res_arr.append(temp)
        return res_arr
    
    
    str = "a\a\b\f\n\r\t\v\c\d\e\f\i"
    print(split_str(str))    
    

提交回复
热议问题