[英]How to for loop in print statement
I am trying to format my output to print with 7 whitespaces at the beginning. 我正在尝试格式化输出以在开始时使用7个空格打印。
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
. 如果只需要7个空格(不包括7个字符的总宽度,包括值),则可能需要手动添加
" "
或" " * 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
: 如果您需要为各个数字设置特殊格式(例如将其填充到通用宽度),则只需进行
format
调用即可,而不是使用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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.