I am trying to format my output to print with 7 whitespaces at the beginning.
for i in range(1,17):
print(i, end=' ')
How could I include that in a formatted statement? For example:
print("{0:>7}".format(for loop to print horizontal line of numbers)
If you want exactly 7 spaces (not a total width of 7 characters, including the value), you probably want to manually add " "
or " " * 7
. How about:
print(" "*7 + " ".join(str(i) for i in range(1, 17)))
Output:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
If you need special formatting for the individual numbers (such as padding them to a common width), just make a format
call instead of str
:
print(" "*7 + " ".join(format(i, "2d") for i in range(1, 17)))
Output:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
# ^ ^ ^ ^ ^ ^ ^ ^ ^ note extra spaces padding the 1-digit numbers to width 2
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.