Python Forum
transform list to tuple with - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: transform list to tuple with (/thread-6565.html)



transform list to tuple with - takaa - Nov-28-2017

Hi,

summary:
I have this output: [(1,), (2,), (3,), (4,), (5,)]
Question, how can I transform this to: ('1', '2','3','4',5')

Below is my trial

sId = cur1.fetchall()
print(sId)
Output:
[(1,), (2,), (3,), (4,), (5,)]
Here I change everything to an integer list
sId = cur1.fetchall()
sId2 = [x[0] for x in sId]
print(sId2)
Output:
[1, 2, 3, 4, 5]
Then I try to make it a string
try 1:
sId = cur1.fetchall()
sId2 = [x[0] for x in sId]
sId2 = tuple(sId2)
print(sId2)
Output:
(1,2,3,4,5)
try 2:
sId = cur1.fetchall()
sId2 = [x[0] for x in sId]
sId2 = (",".join(str(i) for i in sId2))
print(sId2)
Output:
1,2,3,4,5
Not yet what I need...

Can somebody help me to transform the original [(1,), (2,), (3,), (4,), (5,)] into ('1', '2','3','4',5') ?


RE: transform list to tuple with - snippsat - Nov-28-2017

>>> lst = [(1,), (2,), (3,), (4,), (5,)]
>>> [str(x[0]) for x in lst]
['1', '2', '3', '4', '5']
>>> # If need tuple
>>> tuple([str(x[0]) for x in lst])
('1', '2', '3', '4', '5')



RE: transform list to tuple with - takaa - Nov-28-2017

(Nov-28-2017, 10:38 PM)snippsat Wrote:
>>> lst = [(1,), (2,), (3,), (4,), (5,)]
>>> [str(x[0]) for x in lst]
['1', '2', '3', '4', '5']
>>> # If need tuple
>>> tuple([str(x[0]) for x in lst])
('1', '2', '3', '4', '5')

thanks! works like a charm