Created
April 27, 2020 08:25
-
-
Save gyli/8bf104329dce56a3abbf02b2c2b4f65b to your computer and use it in GitHub Desktop.
Fetch nested bracketed values from string
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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