Below I posted a solution that does not rely on regex. It uses the stack ( list ) to determine if the character is inside the braces { . The regular expression is more elegant, however it can be more difficult to change when changing requirements. Note that the example below also works for nested brackets.
text = "a,b,{'c','d','e','f'},g,h" output='' stack = [] for char in text: if char == '{': stack.append(char) elif char == '}': stack.pop() #Check if we are inside a curly bracket if len(stack)>0 and char==',': output += ';' else: output += char print output
This gives:
'a,b,{'c';'d';'e';'f'},g,h
You can also rewrite this as a map function if you use a global variable for stack :
stack = [] def replace_comma_in_curly_brackets(char): if char == '{': stack.append(char) elif char == '}': stack.pop() #Check if we are inside a curly bracket if len(stack)>0 and char==',': return ';' return char text = "a,b,{'c','d','e','f'},g,h" print ''.join(map(str, map(replace_comma_in_curly_brackets,text)))
Regarding performance, when I run the above two methods and solve the regular expression suggested by @stribizhev on the test line at the end of this post, I get the following timings:
- Regular Expression (@stribizshev): 0.38 seconds
- Card Function: 26.3 seconds
- Per cycle: 251 seconds
This is a test string with a length of 55,300.00 characters:
text = "a,able,about,across,after,all,almost,{also,am,among,an,and,any,are,as,at,be,because},been,but,by,can,cannot,could,dear,did,do,does,either,else,ever,every,for,from,get,got,had,has,have,he,her,hers,him,his,how,however,i,if,in,into,is,it,its,just,least,let,like,likely,may,me,might,most,must,my,neither,no,nor,not,of,off,often,on,only,or,other,our,own,rather,said,say,says,she,should,since,so,some,than,that,the,their,them,then,there,these,they,this,tis,to,too,twas,us,wants,was,we,were,what,when,where,which,while,who,whom,why,will,with,would,yet,you,your" * 100000