How can I use line.replace to add space around any brackets in a string that are elements in another bracket set, through a loop?

StackOverflow https://stackoverflow.com/questions/18010884

Question

brackets = {')', '(', '{', '}', '[', '>', ']', '<'}

string_line = <[2{12.5 6.0}](3 -4 5)>'

Basically I have to add space around any brackets in a string_line for brackets that are in the set. e.g. '[' becomes ' [ ' Assuming that I wouldn't know what brackets it contains, how can i avoid repeating line.replace 8 times? (there are 8 types of brackets)

Thanks!

Was it helpful?

Solution

You could try using regular expressions. The stupid while loop at the end is due to fact that I do not know how to replace overlapping matches. I would be grateful for any advice on this item.

#! /usr/bin/python3

import re

string_line = '<[2{12.5 6.0}](3 -4 5)>'

while True:
    string_line, count = re.subn ('[{}<>\[\]()][{}<>\[\]()]', lambda x: '{} {}'.format (*x.group () ), string_line)
    if not count: break

print (string_line)

This yields:

< [2{12.5 6.0} ] (3 -4 5) >

Basically inserting a whitespace between two following brackets. If this is not the expected behaviour please let me know the expected output.

OTHER TIPS

try with list operations:

import functools
def replaceif(x):
    if x in brackets:
        x=' '+x+' '
    return x
brackets = [')', '(', '{', '}', '[', '>', ']', '<']
string_line = '<[2{12.5 6.0}](3 -4 5)>'
print(functools.reduce(lambda x,y: replaceif(x)+replaceif(y), string_line))
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top