In python, how can I use regex to replace square bracket with parentheses
I have a list: list = [1,2,3]
. And I would like to convert it to a string with parentheses: string = (1,2,3)
.
I am currently using the replace string string = str(list).replace('[','(').replace(']',')')
. But I think there is a better way to use regex.sub. But I have no idea how to do it. Many thanks
If you do have a list then:
>>> s = [1,2,3]
>>> str(tuple(s))
'(1, 2, 3)'
You can use instead string.maketrans
- I'm sure it's faster than sequence str.replace
and it scales better for more single character replacements.
>>> import string
>>> table = string.maketrans('[]','()')
>>> s = "[1, 2, 3, 4]"
>>> s.translate(table)
'(1, 2, 3, 4)'
You can even use this to remove characters from the original string by passing an optional second argument to str.translate
:
>>> s = str(['1','2'])
>>> s
"['1', '2']"
>>> s.translate(table,"'")
'(1, 2)'
In python3.x, the string module is gone and you can access maketrans
via the inline str
:
table = str.maketrans('[]','()')
str([1,2,3]).replace('[','(').replace(']',')')
Should work well for you, and as far as I know, it is both forward and backward compatible.
In terms of reuse, you can use the following function on several different types of strings to change where they start and end:
def change(str_obj,start,end):
if isinstance(str_obj,str) and isinstance(start,str) and isinstance(end,str):
pass
else:
raise Exception("Error, expecting a 'str' objects, got %s." % ",".join(str(type(x)) for x in [str_obj,start,end]))
if len(str_obj)>=2:
temp=list(str_obj)
temp[0]=start
temp[len(str_obj)-1]=end
return "".join(temp)
else:
raise Exception("Error, string size must be greater than or equal to 2. Got a length of: %s" % len(str_obj))
There are a billion ways to do this, as all the answers show. Here's another one:
my_list = [1,2,3]
my_str = "(%s)" % str(my_list).strip('[]')
or to make it recyclable:
list_in_parens = lambda l: "(%s)" % str(l).strip('[]')
my_str = list_in_parens(my_list)
Try the following:
'({0})'.format(', '.join(str(x) for x in list))
By the way, it's not worth naming your own variables list
as it collides with the built-in function. string
May also conflict with a module of the same name.
If you really want to use regex I think this will work. But the other solutions posted are probably more efficient and / or easier to use.
import re
string = str(list)
re.sub(r"[\[]", "(", string)
re.sub(r"[\]]", ")", string)
@mgilson something like this do you mean?
def replace_stuff(string):
string_list = list(string)
pattern = re.compile(r"[\[\]]")
result = re.match(pattern, string)
for i in range(len(result.groups())):
bracket = result.group(i)
index = bracket.start()
print(index)
if bracket == "[":
string_list[index] = "("
else:
string_list[index] = ")"
return str(string_list)
This doesn't quite work, for some reason len (result.groups ()) is always 0, even though the regex should find matches. So it was not possible to test if this is faster, but since I could not get it to work, I was unable to test it. I have to go to bed now, so if someone can fix this, go ahead.