Search code examples
pythonoutputclipping

Python clipping database returned variables


I'm busy with a script to get some data from the database and arrange it for output later and I would like to know how to clip the variables being returned

I have my script

# CONNECT TO DATABASE
#=====================================================================
varPgSQL = connectToDatabase()

# PREPARE SQL STATEMENTS
#=====================================================================
cur_users = varPgSQL.cursor()
cur_users.execute("prepare cur_users as " +
                  "select * from users " +
                  "where usr_idno > $1")

cur_details = varPgSQL.cursor()
cur_details.execute("prepare cur_details as " +
                    "select * from details " +
                    "where dtl_usr_idno = $1")

# EXECUTE SQL STATEMENTS
#=====================================================================
la_results = []

cur_users.execute("execute cur_users(%s)", str(0))
for lr_user in cur_users:

    cur_details.execute("execute cur_details(%s)", str(lr_user[0]))
    for lr_detail in cur_details:

        # STORE RESULTS
        la_results.append({
            "usr_idno": lr_user[0],
            "usr_name": lr_user[1],
            "dtl_usr_idno": lr_detail[0],
            "dtl_usr_accn": lr_detail[1],
            "dtl_usr_accs": lr_detail[2]
        })

# CLOSE CONNECTION
#=====================================================================
varPgSQL.close()

# CHECK RESULTS
#=====================================================================
for lr_result in la_results:
    print(
        " | " +
        lr_result["usr_name"] +
        " | " +
        lr_result["dtl_usr_accn"] +
        " | " +
        lr_result["dtl_usr_accs"] +
        " | "
    )

The output of this code though is not clipping the variables, the output is

| mavis           | service acc     | active     |

Which is what I expected because it's the length of the fields in the database but is it possible to clip the variables for output to achieve

| mavis | service acc | active |

Solution

  • If the gaps are being created by whitespace you can use the built in String method strip()

    If its is a database artifact you may have to give us more information.