Yan
Yan

Reputation: 81

How to convert my list variable from a tuple to a string

i am getting the following error:

index 0 has type 'tuple' but 'str' is expected

My list variable looks like this:

[('304',), ('316',), ('303',), ('BS S130',), ('Do Not Use',), ('17-4PH',), ('431S29',), ('416',), ('304',), ('316',), ('S143D',), ('15/5PH-H1025',), ('304S11',), ('316S11',), ('304L',), ('316L',), ('304S16',), ('BS S527',), ('316L',), ('316',), ('Misc',)]

def stainless_list(self):
    stainless_getlist = []

    content = 'SELECT grade FROM stainless ORDER BY prefix ASC'
    res = conn.execute(content)
    for row_index, row_data in enumerate(res):
        stainless_getlist.append(row_data)

    conn.close

    self.comboBox_2.clear()
    self.comboBox_2.addItems(stainless_getlist)

    print(stainless_getlist)
    return

How do i declare my list as a string instead of tuple so that it attaches to my combobox correctly?

Upvotes: 2

Views: 148

Answers (2)

Bob McCormick
Bob McCormick

Reputation: 225

Your list is a list of tuples, where each tuple is a row of data. What may be confusing is that the output of your select is a list of rows, with only one value in each row. Try this:

for row in res:
   stainless_getlist.append( row[0] )

The 1st row is tuple containing one string ('304',) not just a string '304'.

Upvotes: 1

blhsing
blhsing

Reputation: 106618

You can unpack the first item of each tuple as you iterate over the rows (and you don't need to enumerate as you are not using the row index).

Change:

for row_index, row_data in enumerate(res):
    stainless_getlist.append(row_data)

to:

for item, in res:
    stainless_getlist.append(item)

Upvotes: 3

Related Questions