Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to slice strings inside tuples inside lists?

I’m working with an SQL database to get a list of primary key ids, however when I print the list, it prints an extra comma along with it. Is there a way to remove or access just the numbers in the list?

Here is what I have:

import mysql.connector

con = mysql.connector.connect(host='localhost',
                              database='database',
                              user='root',
                              password=database_pw)
cursor = con.cursor()
query = """select playerid from nba_players;"""
cursor.execute(query)
playerids = cursor.fetchall()
print(playerids)

Here is the output:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[(20000441,),
 (20000442,),
 (20000443,),
 (20000452,),
 (20000453,),
 (20000455,),
 (20000456,),
 (20000457,),
 (20000466,),
 (20000468,),
 (20000471,),
 (20000474,),
 (20000482,),
 (20000483,),
 (20000485,),
 (20000486,),
 (20000492,),
 (20000497,),
 (20000500,),
 (20000515,),
 (20000516,),
 (20000517,),
 (20000522,),
 (20000539,),
 (20000544,),
...

And here is the output that I’m looking for

[(20000441),
 (20000442),
 (20000443),
 (20000452),
 (20000453),
 (20000455),
 (20000456),
 (20000457),
 (20000466),
 (20000468),
 (20000471),
 (20000474),
 (20000482),
 (20000483),
 (20000485),
 (20000486),
 (20000492),
 (20000497),
 (20000500),
 (20000515),
 (20000516),
 (20000517),
 (20000522),
 (20000539),
 (20000544),
...

>Solution :

You can use a list comprehension:

[playerid[0] for playerid in playerids]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading