Skip to content

Instantly share code, notes, and snippets.

@gyli
Created April 27, 2020 08:25
Show Gist options
  • Save gyli/8bf104329dce56a3abbf02b2c2b4f65b to your computer and use it in GitHub Desktop.
Save gyli/8bf104329dce56a3abbf02b2c2b4f65b to your computer and use it in GitHub Desktop.
Fetch nested bracketed values from string
template = """head{var1}middle{var2{nested}}end"""
def parenthetic_contents(string):
"""Generate parenthesized contents in string as pairs (level, contents)."""
stack = []
for i, c in enumerate(string):
if c == '{':
stack.append(i)
elif c == '}' and stack:
start = stack.pop()
yield (len(stack), string[start + 1: i])
list(parenthetic_contents(template))
# [(0, 'var1'), (1, 'nested'), (0, 'var2{nested}')]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment