-
-
Save mumuxme/0e92da712e3e07ae1caf24746ae40e5a to your computer and use it in GitHub Desktop.
Remove text between brackets
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
| # from https://stackoverflow.com/questions/14596884/remove-text-between-and-in-python | |
| def remove_text_inside_brackets(text, brackets="()[]"): | |
| count = [0] * (len(brackets) // 2) # count open/close brackets | |
| saved_chars = [] | |
| for character in text: | |
| for i, b in enumerate(brackets): | |
| if character == b: # found bracket | |
| kind, is_close = divmod(i, 2) | |
| count[kind] += (-1)**is_close # `+1`: open, `-1`: close | |
| if count[kind] < 0: # unbalanced bracket | |
| count[kind] = 0 # keep it | |
| else: # found bracket to remove | |
| break | |
| else: # character is not a [balanced] bracket | |
| if not any(count): # outside brackets | |
| saved_chars.append(character) | |
| return ''.join(saved_chars) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment