除了python中的某些字符之外,如何用“,”拆分字符串?

时间:2017-06-08 18:48:10

标签: python split

如何用“,”拆分字符串除了python中的某些字符之间? 我的数据如下:

('00012+1357','LSC   2','Aa,Ab',2014,2014,   2,185,185,  0.2,  0.2,10.7,13.1,'M0.5',+019,+135,NULL,NULL,NULL,NULL,'000113.19+135830.3')

我需要将它们拆分为“,”除了'Aa,Ab'

结果应为:

("00012+1357" "LSC   2" "Aa,Ab" "2014" "2014" "2" "185" "185" "0.2"  "0.2" "10.7" "13.1" "M0.5" "+019" "+135" "NULL" "NULL" "NULL" "NULL" "000113.19+135830.3")

你知道怎么做吗?

3 个答案:

答案 0 :(得分:0)

看来你正在寻找''.join():

the_string = ('00012+1357','LSC   2','Aa,Ab',2014,2014,   2,185,185,  0.2,  0.2,10.7,13.1,'M0.5', 19, 135, 'NULL','NULL','NULL','NULL','000113.19+135830.3')

the_string = map(str, the_string)

new_string = (' '.join(i for i in the_string))

答案 1 :(得分:0)

您似乎正在尝试解析CSV数据。 csv模块应该足够,并且能够处理所有这些边缘情况。

答案 2 :(得分:0)

我会尝试一些代码。 如果字符串在needle之外,则按quotes拆分字符串。 假设needlequotes都是一个字符长。

#!python3

def splitExceptBetween(istr, needle, quotes):
    inside = -1
    res = []
    oldt = 0
    for index, letter in enumerate(istr):
        if letter==quotes:
            inside = -inside
        elif letter==needle and inside == -1:
            res.append(istr[oldt:index])
            oldt = index+1
    if oldt<len(istr):
        res.append(istr[oldt:])
    return res

istr = "as'das'd.asdas'd.a'sdas.drth..rt'h.r'th.'"
print(splitExceptBetween(istr, ".", "'"))
istr = "00012+1357,LSC   2,'Aa,Ab',2014,2014,   2,185,185,  0.2,  0.2,10.7,13.1,M0.5,+019,+135,NULL,NULL,NULL,NULL,000113.19+135830.3"
print(splitExceptBetween(istr, ",", "'"))