-1
    selectedTeam = str(self.comboBox_2.currentText())
    sql2="select Players from TeamFormed where Name='"+selectedTeam+"';"
    curt=Teams.cursor()
    curt.execute(sql2)
    players=curt.fetchone()
    #Just to check the type length and contents
    print(type(players))
    print(players)
    print(len(players))

    ast.literal_eval(players[0])

    #Just to check the type length and contents
    print(type(players))
    print(players)
    print(len(players))

I have a tuple like this

("['Virat Kohli', 'A B de villiers', 'K L Rahul', 'Aron Finch', 'Glenn Maxwell', 'Suresh Raina', 'Shikhar Dhawan', 'Rohit Sharma', 'B Kumar', 'James Anderson', 'M Shami', 'Jasprit Bumrah']",)

which produced after fetching data from database. Length of this tuple is showing 1. I want to convert this to a list of length 12.

  • 1
    Can you show the code fetching from the database? It seems like you erroneously converted to `str`. – Reut Sharabani Jul 31 '18 at 12:13
  • `ast.literal_eval(("['Virat Kohli', 'A B de villiers', 'K L Rahul', 'Aron Finch', 'Glenn Maxwell', 'Suresh Raina', 'Shikhar Dhawan', 'Rohit Sharma', 'B Kumar', 'James Anderson', 'M Shami', 'Jasprit Bumrah']",)[0])` – Chris_Rands Jul 31 '18 at 12:14
  • It is not available to me directly as a list it is in a variable named players fetched from the database.I have done it several times but it's not working.Also i am new to Python. – Manish Trivedi Jul 31 '18 at 12:34
  • You are converting to `str` needlessly either when you are inserting data to the database, or when you are fetching data from the database. There is no reason for this list to be stringified. You are not fixing the right problem, you are fixing a symptom. – Reut Sharabani Jul 31 '18 at 12:37
  • Actually after converting it to a list i have to insert it in a listWidget that is why i am converting it to a list.If i am trying to insert in the listWidget in this way only then it shows up in a single line and not as a list. – Manish Trivedi Jul 31 '18 at 12:47

2 Answers2

0

You can use literal_eval:

import ast
l = ("['Virat Kohli', 'A B de villiers', 'K L Rahul', 'Aron Finch', 'Glenn Maxwell', 'Suresh Raina', 'Shikhar Dhawan', 'Rohit Sharma', 'B Kumar', 'James Anderson', 'M Shami', 'Jasprit Bumrah']",)

k = ast.literal_eval(l[0])
# ['Virat Kohli', 'A B de villiers', 'K L Rahul', 'Aron Finch', 'Glenn Maxwell', 'Suresh Raina', 'Shikhar Dhawan', 'Rohit Sharma', 'B Kumar', 'James Anderson', 'M Shami', 'Jasprit Bumrah']
len(k) # 12
ᴀʀᴍᴀɴ
  • 4,443
  • 8
  • 37
  • 57
0

Here:

a = ("['Virat Kohli', 'A B de villiers', 'K L Rahul', 'Aron Finch', 'Glenn Maxwell', 'Suresh Raina', 'Shikhar Dhawan', 'Rohit Sharma', 'B Kumar', 'James Anderson', 'M Shami', 'Jasprit Bumrah']",)
exec('b = ' + a[0])

for c in b:
    print(c)

EDIT

Or use @ᴀʀᴍᴀɴ's solution, i think it's better.

CodiMech25
  • 443
  • 3
  • 9