0

I am reading data from a MySQL database and want to print it to the screen.

I use:

import MySQLdb
conn = MySQLdb.connect(host='localhost',user='root',passwd='passwd',db='test',charset='utf8')
cursor = conn.cursor()
cursor.execute('select cust_name,cust_address,cust_city,cust_state from Customers')
numrows = int(cursor.rowcount)
for i in range(numrows):
    row =  cursor.fetchone()
    print "%s  %s  %s   %20s" %(row[0],row[1],row[2],row[3])
cursor.close()
conn.close()

The result is like this:

Village Toys  200 Maple Lane  Detroit            MI

Kids Place  333 South Lake Drive  Columbus                     OH

Fun4All  1 Sunny Place  Muncie                     IN

Fun4All  829 Riverside Drive  Phoenix                     AZ

The Toy Store  4545 53rd Street  Chicago                     IL

How can i make it left justified?

2 Answers 2

1

Assuming you only want to align the last column, do it like this:

print "%s  %s  %s   %-20s" %(row[0],row[1],row[2],row[3])

The --sign justifies it to the left.

Sign up to request clarification or add additional context in comments.

2 Comments

@user1773219 Please, put the result wanted in the question. In the comments the formatting is lost.
thank you very much . I am sorry ,I couldn't Clearly expressed the question. I think this answer is great print('{row[0]:20}{row[1]:20}{row[2]:20}{row[3]:20}'.format(row=row))
0

Also, there is a new formatting syntax in Python.

As I understand, you want every column to have the same indentation. This can be achieved by specifying the space each column should occupy. Because now first 3 strings are put to consume as little as possible of the target string, and only the last one takes 20 symbols. If you specify the length of each string, you will get the output in the resulting string well aligned.

Try this:

print('{row[0]:20}{row[1]:20}{row[2]:20}{row[3]:20}'.format(row=row))

The numbers 20 in the curly braces denote the length of each field.

1 Comment

@user1773219 Please, show the example of the output you want. Show this example in the question (click edit) and add this example.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.