Skip to content

Instantly share code, notes, and snippets.

@Ogaday
Created October 21, 2019 17:31
Show Gist options
  • Select an option

  • Save Ogaday/6dd447ead596efc1c916a97e877516ad to your computer and use it in GitHub Desktop.

Select an option

Save Ogaday/6dd447ead596efc1c916a97e877516ad to your computer and use it in GitHub Desktop.
Rebracer

Python Kata by @nhumrich of the Pythondev Slack communtiy.

Write a function that takes in a string, and returns a string with everything inside curly brackets {} removed. Example: hello {world} returns hello {}. Example 2: {hello} {world} returns {} {}

Only submissions that DO NOT use regex will be accepted for taco's

tacos for: 1st, cleanest, shortest, fastest, my choice

nested doesn't count. So { hello {something} there} should return: {}

LEFT = '{'
RIGHT = '}'
COMPLETE = '{}'
def replace_braces(string):
"""
Replace characters adjacent to braces.
"""
for token in (tokens := set(string)):
if (substring := LEFT + token) != COMPLETE:
string = string.replace(substring, LEFT)
if (substring := token + RIGHT) != COMPLETE:
string = string.replace(substring, RIGHT)
return string
def rebrace(string):
"""
Remove all content between curly braces.
>>> parse('hello, {world}')
'hello, {}'
>>> parse('{hello {world}}')
'{}'
"""
while (replaced := replace_braces(string)) != string:
string = replaced
return replaced
OPEN = '{'
CLOSE = '}'
def rebrace(string):
"""
Remove all content between curly braces.
>>> parse('hello, {world}')
'hello, {}'
>>> parse('{hello {world}}')
'{}'
"""
kept = []
stack = []
for token in string:
if token == OPEN:
if not stack:
kept.append(token) # Only add outermost brace
stack.append(token) # Open braces
if token == CLOSE:
stack.pop(-1) # Close braces
if not stack:
kept.append(token)
new_string = ''.join(kept)
return new_string
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment