+ 4

Regex Sub

Please help with this code. I need to replace what is inside the square brackets with provided input for example r'[]' will change to r'[$#]' if user provides $# as input More description within. https://code.sololearn.com/c9fn1fDCxcZ4/?ref=app

21st Jun 2020, 4:32 PM
Tomiwa Joseph
Tomiwa Joseph - avatar
9 odpowiedzi
+ 4
Ok, how about this? def subs(a,b=[]): if b: a = re.sub(f"[{''.join(b)}]",'',a) return a
21st Jun 2020, 9:16 PM
Russ
Russ - avatar
21st Jun 2020, 4:48 PM
arieh
+ 3
import re a = 're$gex$es a!re$ !int$er$est!ing' b = re.sub(r'[!$]','',a) print(b) print() def subs(a, b=''): # the 'b='' is needed for your last 'subs'. p = re.sub(b,'',a) return p print(subs('ple#ase$ h&elp #m$e', '[#
amp;]')) print(subs('i! n$eed h$elp', '[!$]')) print(subs('thank you')) print ()
21st Jun 2020, 4:51 PM
rodwynnejones
rodwynnejones - avatar
+ 3
So is this what you need? def subs(a,b=[]): if b: a = re.sub(f"[{b[0]}]",'',a) return a
21st Jun 2020, 6:34 PM
Russ
Russ - avatar
+ 2
arieh No. Plus, you can't change test cases only your code
21st Jun 2020, 6:05 PM
Tomiwa Joseph
Tomiwa Joseph - avatar
+ 2
rodwynnejones the second parameter is a list not a string. ['!#'] or ['!','#'] not '[!#]'
21st Jun 2020, 6:07 PM
Tomiwa Joseph
Tomiwa Joseph - avatar
+ 2
Russ Yes. Absolutely. But what if the b parameter is like this [ '#', '!' ] , do I join then split again so it can be b[0]?
21st Jun 2020, 8:58 PM
Tomiwa Joseph
Tomiwa Joseph - avatar
+ 2
Russ Amazing, thanks.
21st Jun 2020, 10:03 PM
Tomiwa Joseph
Tomiwa Joseph - avatar
+ 2
Thanks guys.
21st Jun 2020, 10:03 PM
Tomiwa Joseph
Tomiwa Joseph - avatar