I am having some trouble with aligning things in my output. Down below I have copied the expected output and the output my code gives me. It is very similar, however, the numbers aren't aligned correctly. My numbers would align to the right (and this first column can only be as long as the longest number in this column). What am I forgetting in my code?
Expected:
1 aggc tgtc aatg
13 ctag gcat agaa
25 gtcg tgct gtag
37 agat agtc tgat
49 agtc gc
Got:
1 aggc tgtc aatg
13 ctag gcat agaa
25 gtcg tgct gtag
37 agat agtc tgat
49 agtc gc
Here is the code in which this problem occurs. I have left out some lines for simplicity, denoted by (...):
for block in blocks:
(...)
to_return += f'{str(index_row): >} {block_row}\n'
# print our final line after iterating through all the blocks
(...)
to_return += f'{str(index_row): >} {block_row}'
return to_return
I thought that using an f-string with the ">" sign would align my numbers to the right. My guess is that I need a number after the ">" sign. The thing is, I don't know beforehand which number, since the width of this first column should be as long as the largest number in my output (and I don't know how long this number will be).
Thank you for any help and tips!
EDIT: My guess is I will need to use a number after the > sign. Since I will have to calculate this number and store it in a variable, can I use a variable name instead of a number, like this:
to_return += f'{str(index_row):>length} {block_row}\n'
This line gives a Value error. Is there a way this can work?
Once you got the length of the largest number in a variable, you need to wrap it in {}
like this:
to_return += f"{index_row:>{length}} {block_row}\n"
Example:
blocks = [(1, "aggc"), (13, "tgtc"), (135, "aatg")]
length = 3
to_return = ""
for index_row, block_row in blocks:
to_return += f"{index_row:>{length}} {block_row}\n"
print(to_return.rstrip())
Example output:
1 aggc
13 tgtc
135 aatg