我有一个如下字符串:
test_string = "test:(apple:orange,(orange:apple)):test2"
仅当括号中不包含“:”时,我才想将其替换为“:”。
所需的输出是“ test /(apple:orange,(orange:apple))/ test2”
这如何在Python中完成?
答案 0 :(得分:4)
您可以使用下面的代码来达到预期的输出量
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))
答案 1 :(得分:2)
带有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'
\((?:[^()]++|(?0))++\)
递归匹配一对括号
(*SKIP)(*F)
以避免替换前面的模式
|:
将:
指定为替代匹配答案 2 :(得分:0)
代码:
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
警告:正如评论指出的那样,如果有多个不同的括号,这将不起作用:(