jofri jofri -4 years ago 101
Python Question

Elegant way to strip() python

I have to strip() my output of the DB with Python and it already works. But is there a more elegant way to do this?

Here is my code:

import MySQLdb
conn= MySQLdb.connect("localhost","root","testPW","MixOMat")
c=conn.cursor()
c.execute("SELECT Zutat1 FROM Rezepte WHERE RezeptID=1")
z1=str(c.fetchall())
z1=z1.strip("(")
z1=z1.rstrip(")")
z1=z1.rstrip(",")
z1=z1.rstrip(")")
z1=z1.rstrip(",")
z1=z1.rstrip("L")
print(z1)

Answer Source

First, .strip parameter is the characters you want to remove, so you only need 2 calls

z1 = z1.strip('(').rstrip(')L')

Second, you're doing it wrong, the correct way to fetch your data should (I think) be:

c.execute("SELECT Zutat1 FROM Rezepte WHERE RezeptID=1")
(z1, ) = c.fetchone()

Note that I'm assuming you only have one row to retrieve

That will directly retrieve one integer instead of a string representation

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download