Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In python, how can I use regex to replace square bracket with parentheses

Tags:

python

regex

I have a list :list = [1,2,3]. And I would like to convert that into a string with parentheses: string = (1,2,3).

Currently I am using string replace string = str(list).replace('[','(').replace(']',')'). But I think there is a better way using regex.sub. But I have no idea how to do it. Thanks a lot

like image 982
Winston Avatar asked Feb 19 '13 02:02

Winston


People also ask

How do you replace brackets in Python?

In Python, we use the replace() function to replace some portion of a string with another string. We can use this function to remove parentheses from string in Python by replacing their occurrences with an empty character. To achieve this, we will use the replace() function two times in quick succession.

How do you define brackets in regex?

By placing part of a regular expression inside round brackets or parentheses, you can group that part of the regular expression together. This allows you to apply a quantifier to the entire group or to restrict alternation to part of the regex. Only parentheses can be used for grouping.

How do you use square brackets in regex Python?

[] - Square brackets Here, [abc] will match if the string you are trying to match contains any of the a , b or c . You can also specify a range of characters using - inside square brackets. [a-e] is the same as [abcde] . [1-4] is the same as [1234] .

How do you replace square brackets in a string?

String str = "[Chrissman-@1]"; str = replaceAll("\\[\\]", ""); String[] temp = str. split("-@"); System. out. println("Nickname: " + temp[0] + " | Power: " + temp[1]);


5 Answers

If you do indeed have a list, then:

>>> s  = [1,2,3]
>>> str(tuple(s))
'(1, 2, 3)'
like image 123
Jon Clements Avatar answered Oct 11 '22 17:10

Jon Clements


You could use string.maketrans instead -- I'm betting it runs faster than a sequence of str.replace and it scales better to 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 gain access to maketrans via the str builtin:

table = str.maketrans('[]','()')
like image 24
mgilson Avatar answered Oct 11 '22 18:10

mgilson


There are a billion ways to do this, as demonstrated by all the answers. Here's another one:

my_list = [1,2,3]
my_str = "(%s)" % str(my_list).strip('[]')

or make it recyclable:

list_in_parens = lambda l: "(%s)" % str(l).strip('[]')
my_str = list_in_parens(my_list)
like image 43
ExperimentFailed Avatar answered Oct 11 '22 18:10

ExperimentFailed


str([1,2,3]).replace('[','(').replace(']',')')

Should work for you well, and it is forward and backward compatible as far as I know.

as far as re-usability, you can use the following function for multiple different types of strings to change what they start and end with:

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))
like image 36
IT Ninja Avatar answered Oct 11 '22 19:10

IT Ninja


All you need is:

"(" + strng.strip('[]') + ")"

It works for both single element and multi-element lists.

>>> lst = [1,2,3]
>>> strng = str(lst)
>>> "(" + strng.strip('[]') + ")"
'(1, 2, 3)'


>>> lst = [1]
>>> strng = str(lst)
>>> "(" + strng.strip('[]') + ")"
'(1)'
like image 41
apkul Avatar answered Oct 11 '22 17:10

apkul