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
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('[]','()')
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))
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)
Try this:
'({0})'.format(', '.join(str(x) for x in list))
By the way, it's not a good idea to name your own variables list
since it clashes with the built-in function. Also string
can conflict with the module of the same name.
If you really want to use regex I guess this would work. But the other posted solutions are probably more efficient and/or easy to use.
import re
string = str(list)
re.sub(r"[\[]", "(", string)
re.sub(r"[\]]", ")", string)
@mgilson something like this 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)
It doesn't quite work, for some reason len(result.groups()) is always 0 even though the regex should find matches. So couldn't test whether this is faster but because I couldn't get it to work I couldn't test it. I have to leave for bed now so if someone can fix this go ahead.
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)'
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.