将字符串拆分为某个索引

时间:2014-03-19 13:32:54

标签: python split

如果我有一个字符串,我想将它拆分为'。'哪个不包含在括号内,我该怎么做。

'(1.2).(2.1)'获取['(1.2)', '(2.1)']

'(1.2).2'获取['(1.2)', '2']

'1.(1.2)'获取['1', '(1.2)']

4 个答案:

答案 0 :(得分:3)

这不能解决一般问题,但适用于您的示例:

>>> import re
>>> re.split(r'(?<=\))\.', '(1.2).(2.1)')
['(1.2)', '(2.1)']
>>> re.split(r'(?<=\))\.', '(1.2).2')
['(1.2)', '2']

这会在关闭括号后的任何句号上拆分字符串。

答案 1 :(得分:3)

该程序假设输入始终有效,但包含正确处理条件的条件相当容易。

def custom_split(data):
    element, opened, result = "", 0, []
    for char in data:
        # Immediately following if..elif can be shortened like this
        # opened += (char == ")") - (char == "(")
        # Wrote like that for readability

        if char == ")":
            opened -= 1
        elif char == "(":
            opened += 1

        if char == "." and opened == 0 and element != "":
            result.append(element)
            element = ""
        else:
            element += char

    if element != "":
        result.append(element)
    return result

print custom_split('(1.2).(2.1)')
print custom_split('(1.2).2')
print custom_split('2.2')
print custom_split('(2.2)')
print custom_split('2')

<强>输出

['(1.2)', '(2.1)']
['(1.2)', '2']
['2', '2']
['(2.2)']
['2']

答案 2 :(得分:1)

使用re似乎是解决方案:

>>> import re
>>> r = re.compile(r'(?:[^.(]|\([^)]*\))+')
>>> r.findall('(1.2).(2.1)')
['(1.2)', '(2.1)']
>>> r.findall('(1.2).2')
['(1.2)', '2']
>>> r.findall('1.(1.2)')
['1', '(1.2)']

答案 3 :(得分:0)

def split(s, level=0, result=''):
    if s == '':
        if result:
            return [result]
        else:
            return []
    if s.startswith('.') and level == 0:
        return [result] + split(s[1:], 0, '')
    level += s.startswith('(')
    level -= s.startswith(')')
    return split(s[1:], level, result + s[0])

用法:

>>> split('(1.2).(2.1)')
['(1.2)', '(2.1)']
>>> split('(1.2).2')
['(1.2)', '2']
>>> split('1.(1.2)')
['1', '(1.2)']