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
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.
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.
[] - 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] .
String str = "[Chrissman-@1]"; str = replaceAll("\\[\\]", ""); String[] temp = str. split("-@"); System. out. println("Nickname: " + temp[0] + " | Power: " + temp[1]);
If you do indeed have a list, then:
>>> s = [1,2,3]
>>> str(tuple(s))
'(1, 2, 3)'
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('[]','()')
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)
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))
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)'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With