In python3 you can use the format method from string:
print("{:^10.2f}|{:^10.2f}|{:^10.2f}|{:^10.2f}|".format(x,sin(x),cos(x),tan(x)))
Notice that ^ means to center, 10 is the total size of the 'cell' and .2f is to print a float with 2 decimal places, change it according to your needs.
Without using any modules or imports, how can I take the below list and print it as a table?
['Southwest', '0', '0', '0', '0', 'Yes!', 'JetBlue', '20', '35', '75', '125', 'Yikes', 'Alaska Airlines', '25', '25', '125', '155', 'Ooof', 'Delta', '25', '35', '200', '150', 'We Lost Track', 'United', '25', '35', '200', '250', 'Whaaaaat?', 'Am. Airlines', '25', '35', '200', '205', 'Arrrgh!', 'Spirit', '30', '40', '100', '292', 'Really??']
image example of final output:
https://i.ibb.co/zVrmT7v/Screen-Shot-2019-11-24-at-7-35-55-PM.png
In python3 you can use the format method from string:
print("{:^10.2f}|{:^10.2f}|{:^10.2f}|{:^10.2f}|".format(x,sin(x),cos(x),tan(x)))
Notice that ^ means to center, 10 is the total size of the 'cell' and .2f is to print a float with 2 decimal places, change it according to your needs.
First print first 2 lines. Then add this code:
for i in YOUR_LIST:
print '%6.2f | %6.2f | %6.2f | %6.2f'%(i,math.sin(i),math.cos(i),math.tan(i))
Hope this helps!
python Printing a list in a tabular format without modules - Stack Overflow
python - Printing Lists as Tabular Data - Stack Overflow
How do I print a table in python while keeping appopriate space between each element ?
printing table in format without using a library, SQLite 3 python - Stack Overflow
There are some light and useful python packages for this purpose:
1. tabulate
https://pypi.python.org/pypi/tabulate
from tabulate import tabulate
print(tabulate([['Alice', 24], ['Bob', 19]], headers=['Name', 'Age']))
Name Age
------ -----
Alice 24
Bob 19
tabulate has many options to specify headers and table format.
print(tabulate(
[['Alice', 24], ['Bob', 19]],
headers=['Name', 'Age'],
tablefmt='orgtbl'))
| Name | Age |
|--------+-------|
| Alice | 24 |
| Bob | 19 |
2. PrettyTable
https://pypi.python.org/pypi/PrettyTable
from prettytable import PrettyTable
t = PrettyTable(['Name', 'Age'])
t.add_row(['Alice', 24])
t.add_row(['Bob', 19])
print(t)
+-------+-----+
| Name | Age |
+-------+-----+
| Alice | 24 |
| Bob | 19 |
+-------+-----+
PrettyTable has options to read data from csv, html, sql database. Also you are able to select subset of data, sort table and change table styles.
3. texttable
https://pypi.python.org/pypi/texttable
from texttable import Texttable
t = Texttable()
t.add_rows([['Name', 'Age'], ['Alice', 24], ['Bob', 19]])
print(t.draw())
+-------+-----+
| Name | Age |
+=======+=====+
| Alice | 24 |
+-------+-----+
| Bob | 19 |
+-------+-----+
with texttable you can control horizontal/vertical align, border style and data types.
4. termtables
https://github.com/nschloe/termtables
import termtables as tt
string = tt.to_string(
[["Alice", 24], ["Bob", 19]],
header=["Name", "Age"],
style=tt.styles.ascii_thin_double,
# alignment="ll",
# padding=(0, 1),
)
print(string)
+-------+-----+
| Name | Age |
+=======+=====+
| Alice | 24 |
+-------+-----+
| Bob | 19 |
+-------+-----+
with texttable you can control horizontal/vertical align, border style and data types.
Other options
- terminaltables - Easily draw tables in terminal/console applications from a list of lists of strings. Supports multi-line rows.
- asciitable can read and write a wide range of ASCII table formats via built-in Extension Reader Classes.
Some ad-hoc code:
row_format ="{:>15}" * (len(teams_list) + 1)
print(row_format.format("", *teams_list))
for team, row in zip(teams_list, data):
print(row_format.format(team, *row))
This relies on str.format() and the Format Specification Mini-Language.
Hey, i'm a beginner in python and it's been only couple of weeks since i've been into the world of coding. What I want to do is to print a table, by a table I mean a list that contains sublists and I want them to be printed in a form of a table, when printing it using the following code :
for i in range(n+1):
print(*lst[i],end='')
print()The printed table looks like :
1 2 89 92 4 56 84 144 1 5 0 6 6 63 173 242
My concern here is that I want it to be printed in a more organized way, so that it would like :
1 2 89 92 4 56 84 144 1 5 0 6 6 63 173 242
Any help will be appreciated ! Thanks in advance !
Use the string formatting capability:
formatted_row = '{:<10} {:<6} {:>6} {:>6} {:<9} {:<9}'
print(formatted_row.format("Name", "Gender", "Age", "Score", "Date", "Time"))
for Row in Data:
print(formatted_row.format(*Row))
Output:
Name Gender Age Score Date Time
HAMMAD MALE 18 900 07/01/18 13:07:02
HAMMAD MALE 18 850 07/01/18 13:30:11
INDERVEER MALE 18 750 07/01/18 13:35:46
HAMMAD MALE 18 500 07/01/18 13:08:29
HAMMAD MALE 18 400 07/01/18 14:07:29
PARSA MALE 18 300 07/01/18 13:36:58
HADIA FEMALE 19 300 07/01/18 14:09:37
MANAAL FEMALE 18 100 07/01/18 13:51:40
...
Note
In this approach, we hard-code the width of the columns. In order to dynamically adjust the columns width, we will have to do a good deal more works. I hope this will work for you.
Update
In order to dynamically adjust the widths, we need to pass through the data twice: The first time to determine the maximum width for each column, and the second to print.
# Determine the longest width for each column
header = ("Name", "Gender", "Age", "Score", "Date", "Time")
widths = [len(cell) for cell in header]
for row in Data:
for i, cell in enumerate(row):
widths[i] = max(len(str(cell)), widths[i])
# Construct formatted row like before
formatted_row = ' '.join('{:%d}' % width for width in widths)
print('DEBUG: widths={!r}'.format(widths))
print('DEBUG: formatted_row={!r}'.format(formatted_row))
print(formatted_row.format(*header))
for row in Data:
print(formatted_row.format(*row))
Output:
DEBUG: widths=[9, 6, 3, 5, 8, 8]
DEBUG: formatted_row='{:9} {:6} {:3} {:5} {:8} {:8}'
Name Gender Age Score Date Time
HAMMAD MALE 18 900 07/01/18 13:07:02
HAMMAD MALE 18 850 07/01/18 13:30:11
INDERVEER MALE 18 750 07/01/18 13:35:46
...
Once you are happy with the result, you can delete the DEBUG lines. They are there to show how the code works.
For the heading, just select the text you want, like
select 'Name Gender Age ...';
To format the data, use the printf() function (see https://sqlite.org/lang_corefunc.html#printf), like
select printf('%-20s %-6s %2d ....', Name, Gender, Age, ...) from ...;
(Adjust as necessary.)
#Task 3 loan calc
principal=250000
interest_rate=0.04
monthly_payment=1000
payment_by_month=1000
balance=250000
length_of_loan=0
total_paid=0
while balance > 0:
interest = balance * (interest_rate/12)
print(interest)
new_balance = balance + interest
if new_balance < 500:
payment_by_month = new_balance
last_month_payment = payment_by_month
balance = new_balance - payment_by_month
length_of_loan+=1
total_paid+= payment_by_month
if balance < 1:
print(length_of_loan)
print(balance) print(total_paid)
So i've got this loan calculator that calculates the monthly payment, interest, new balance, etc for each month until the balance reaches 0, for the assignment I'm doing I need all of this displayed in a table with the months on the left and I am not allowed to use df from pandas or anything like that. Does anyone know how I would go about doing this, also while the actual computed values can't be rounded the table must be rounded to two decimal places. The table needs to have months, payment, interest, and balance.
Hi Guys,
Please help me out, I am very weak in programming. I have the below code block which prints out all EC2 instances in an AWS account that are not of the latest generation along with the Cloudformation template used to provision them. The code is working fine now, it's just I need the output to be in a table. I tried using tabulate (commented out in the code block below) but the problem is it prints out and repeats the "headers" specified in each row instead of just on the very top, i think this is because of the whole thing is wrapped in for loop, not sure how I can work around it. I was told that the csv module maybe helpful but I looked python doc and it looks like that is for reading data from a .csv file and then processing it using the csv module. If you guyz can edit my code below and paste it here with the modification needed to display the data in a table format, I would be ever grateful to you. Please help me :( :( :(
import boto3
from tabulate import tabulate
ec2 = boto3.resource('ec2')
latestInstanceTypes = ['t3', 'm5', 'c5']
for instance in ec2.instances.all():
if instance.instance_type.split('.')[0] not in latestInstanceTypes:
stack_ids = [x['Value'] for x in instance.tags if x['Key'] == 'aws:cloudformation:stack-id']
stack_id = stack_ids[0] if len(stack_ids) else None
instance_names = [x['Value'] for x in instance.tags if x['Key'] == 'Name']
instance_name = instance_names[0] if len(instance_names) else None
#print(tabulate([[instance.id, instance.platform, instance.instance_type, instance.public_ip_address, instance.image.id, instance.state, stack_id]], headers=['Id', 'Platform', 'Type', 'Public IPv4', 'AMI', 'State', 'CF Template'], tablefmt='orgtbl'))
print(
"Id: {0}\nName: {1}\nType: {2}\nCFTemplate: {3}\nPlatform: {4}\nAMI: {5}\nState: {6}\n".format(
instance.id, instance_name, instance.instance_type, stack_id, instance.platform, instance.image.id, instance.state
)
)