I’m trying to find out if in the format function if I can convert my float to 2 decimal points and have it align in the one line. In the example below I want to align the last element, i’m wondering if I can do something like print("{0:.2f} {1:<60} {{2:.2f}:<8} {3:.2f}".format(item[0], item[1], item[2], item[3])) I’m aware I can use the round function on the 2nd last element and then align it.
item1 = 0.312, "longname2", 123.6, 76.4329
item2 = 0.112, "longname3", 12.6, 12
arr = [item, item1, item2]
for item in arr:
print("{0:.2f} {1:<60} {2:.2f} {3:.2f}".format(item[0], item[1], item[2], item[3]))
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
You can do it by changing the number of spaces between the 2nd and 3rd element of i depending on the number of digits in the 3rd element:
item1 = 0.312, "longname2", 123.6, 76.4329
item2 = 0.112, "longname3", 12.6, 12
arr = [item1, item2]
for i in arr:
print(f"{i[0]:.2f} {i[1]:<{63-len(str(i[2]))}} {i[2]:.2f} {i[3]:.2f}")
Output:
0.31 longname2 123.60 76.43 0.11 longname3 12.60 12.00
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0