Try this approach using the newer str.format syntax. This uses a width of 12, space padded, right aligned.
line_new = '{:>12} {:>12} {:>12}'.format(words[0], words[1], words[2])
Example with the interpreter:
>>> line = "123 456 789"
>>> words = line.split(' ')
>>> line_new = '{:>12} {:>12} {:>12}'.format(words[0], words[1], words[2])
>>> print(line_new)
123 456 789
And here's how to do it using the old % syntax (useful for older versions of Python that don't support str.format):
line_new = '%12s %12s %12s' % (words[0], words[1], words[2])
Answer from Mark Byers on Stack OverflowTry this approach using the newer str.format syntax. This uses a width of 12, space padded, right aligned.
line_new = '{:>12} {:>12} {:>12}'.format(words[0], words[1], words[2])
Example with the interpreter:
>>> line = "123 456 789"
>>> words = line.split(' ')
>>> line_new = '{:>12} {:>12} {:>12}'.format(words[0], words[1], words[2])
>>> print(line_new)
123 456 789
And here's how to do it using the old % syntax (useful for older versions of Python that don't support str.format):
line_new = '%12s %12s %12s' % (words[0], words[1], words[2])
Here is another way how you can format using 'f-string' format:
print(
f"{'Trades:':<15}{cnt:>10}",
f"{'Wins:':<15}{wins:>10}",
f"{'Losses:':<15}{losses:>10}",
f"{'Breakeven:':<15}{evens:>10}",
f"{'Win/Loss Ratio:':<15}{win_r:>10}",
f"{'Mean Win:':<15}{mean_w:>10}",
f"{'Mean Loss:':<15}{mean_l:>10}",
f"{'Mean:':<15}{mean_trd:>10}",
f"{'Std Dev:':<15}{sd:>10}",
f"{'Max Loss:':<15}{max_l:>10}",
f"{'Max Win:':<15}{max_w:>10}",
f"{'Sharpe Ratio:':<15}{sharpe_r:>10}",
sep="\n"
)
This will provide the following output:
Trades: 2304
Wins: 1232
Losses: 1035
Breakeven: 37
Win/Loss Ratio: 1.19
Mean Win: 0.381
Mean Loss: -0.395
Mean: 0.026
Std Dev: 0.56
Max Loss: -3.406
Max Win: 4.09
Sharpe Ratio: 0.7395
What you are doing here is you are saying that the first column is 15 chars long and it's left-justified and the second column (values) is 10 chars long and it's right-justified.
If you joining items from the list and you want to format space between items you can use `` and regular formatting techniques.
This example separates each number by 3 spaces. The key here is f"{'':>3}"
print(f"{'':>3}".join(str(i) for i in range(1, 11)))
output:
1 2 3 4 5 6 7 8 9 10
This is a very basic question, I am in a beginner python course. I am trying to figure out how to align text in print results, but can not for the life of me figure out how to do it properly.
print('\tBoat Repair Program')
#Get input from user.
boatprice = float(input('\nWhat was the initial cost of the boat? $'))
hourfix = float(input('How many hours were spent fixing the boat? $'))
payrate = float(input('What is the hourly pay rate? $'))
partcost = float(input('What was the cost of repair parts for the boat? $'))
#Calculate total repair cost.
totalcost = (hourfix * payrate) + partcost
#Calculate the final value.
finalvalue = boatprice + totalcost
#Print results.
print(f'\nInitial purchase price: ${boatprice:,.2f}'),
print(f'The total cost of repairs: ${totalcost:,.2f}'),
print(f'The final value of boat: ${finalvalue:.2f}')
print('\nGoodbye')
I am trying to line up the results for the final 3 values. I am not sure if I should be using an f string, or alternatively "format(boatprice, '.2f')". I know the value and alignment should go between the colon and comma ${boatprice:HERE,.2f}'), I just cannot figure out how to put the values in so all three are in alignment. I've tried left, center, and right. I apologize for the basic question, I've just lost out on marks on three assignments already. Any help would be greatly appreciated!
You can use String formatting using theFormat Specification Mini-Language.
For instance:
for i in range(len(entries)):
print("{0:>6.2f}\t{1:>6.2f}\t{2:>6.2f}\t{3:>6.2f}".format(*entries[i]))
You get something like that:
Wind Speed Old Formula New Formula Difference
5.00 9.00 4.00 5.10
6.00 5.00 2.00 2.80
7.00 2.00 1.00 0.80
8.00 -1.00 0.00 -1.10
9.00 -3.00 0.00 -2.80
10.00 -5.00 -1.00 -4.30
11.00 -7.00 -2.00 -5.70
Or, using a more pythonic loop:
for entry in entries:
print("{0:>6.2f}\t{1:>6.2f}\t{2:>6.2f}\t{3:>6.2f}".format(*entry))
You could just pad with spaces using str.format().
def draw_padded_string(s, width, align="left"):
if align == "left":
return "{s: <{width}}".format(s=s, width=width)
elif align == "center":
return s.center(width, ' ')
elif align == "right":
return "{s: >{width}}".format(s=s, width=width)
In this case, s is the string and width is the entire width of your column.
You would define this somewhere in your code, probably under your imports just to get it out of your way, but so long as it is defined before you start calling your print statements. This would change your print block a little, too:
width = 13
headers = ["Wind Speed", "Old Formula", "New Formula", "Difference"]
print_headers = []
for header in headers:
print_headers.append(draw_padded_string(header, width))
print("".join(print_headers))
print()
for row in entries:
print_row = []
for data in row:
print_row.append(draw_padded_string(data, width))
print("".join(print_row))
What I did:
- set width at 13 (your widest column right now is 11)
- created lists of each row to be printed
- applied our function to each item on the list
- print the list as a single row using
"".join(list) - changed from using your own integer tracking using
iandjand instead let python iterate over your rows and columns for you
What you might want to do differently:
- Use list comprehension to generate your lists (instead of
for item in list - Adjust your column width based on the actual maximum list as below
column_length = max([len(word) for word in list_of_words])