代码之家  ›  专栏  ›  技术社区  ›  Jack Arnestad

仅当字符不在括号中时替换字符

  •  3
  • Jack Arnestad  · 技术社区  · 6 年前

    我有一根如下的绳子:

    test_string = "test:(apple:orange,(orange:apple)):test2"
    

    我想将“:”替换为“/”,前提是它不包含在任何一组括号中。

    所需输出为“test/(apple:orange,(orange:apple))/test2”

    如何在python中实现这一点?

    3 回复  |  直到 6 年前
        1
  •  2
  •   Sundeep    6 年前

    regex 模块:

    >>> import regex
    >>> test_string = "test:(apple:orange,(orange:apple)):test2"
    >>> regex.sub(r'\((?:[^()]++|(?0))++\)(*SKIP)(*F)|:', '/', test_string)
    'test/(apple:orange,(orange:apple))/test2'
    
        2
  •  4
  •   Mayur    6 年前

    您可以使用下面的代码来实现预期输出

    def solve(args):
        ans=''
        seen = 0
        for i in args:
            if i == '(':
                seen += 1
            elif i== ')':
                seen -= 1
            if i == ':' and seen <= 0:
                ans += '/'
            else:
                ans += i
        return ans
    
    test_string = "test:(apple:orange,(orange:apple)):test2"
    print(solve(test_string))
    
        3
  •  0
  •   farkas    6 年前
    1. 查找第一个左括号
    2. 查找最后一个右括号
    3. 在第一个左括号前将every“:”替换为“/”
    4. 不要对中间部分做任何事
    5. 在最后一个右括号后,将每个“:”替换为“/”
    6. 把这三个子串放在一起

    代码:

    test_string = "test:(apple:orange,(orange:apple)):test2"
    first_opening = test_string.find('(')
    last_closing = test_string.rfind(')')
    result_string = test_string[:first_opening].replace(':', '/') + test_string[first_opening : last_closing] +  test_string[last_closing:].replace(':', '/')
    print(result_string)
    

    输出:

    test/(apple:orange,(orange:apple))/test2
    

    警告:正如注释所指出的,如果有多个不同的括号,则此操作将不起作用:(