我有一个如下的字符串:
test_string = "test:(apple:orange,(orange:apple)):test2"
我希望将“:”替换为“/”,但仅当它不包含在任何一组括号中时。
期望的输出是“test/(apple:orange,(orange:apple))/test2”。
如何在Python中实现这个目标?
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))
>>> import regex
>>> test_string = "test:(apple:orange,(orange:apple)):test2"
>>> regex.sub(r'\((?:[^()]++|(?0))++\)(*SKIP)(*F)|:', '/', test_string)
'test/(apple:orange,(orange:apple))/test2'
{...}
中,而不是圆括号,该怎么办? - Jack Arnestad(?
开头的对。 - Sundeep代码:
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
警告:正如注释所指出的那样,如果有多个不同的括号,这种方法将无法工作 :(
(apple:orange):test:(orange:apple)
)。 - Amadan
(
时计数器加一,在遇到)
时减一,如果字符匹配且计数器为零,则替换。祝实现愉快! - Klaus D.