python - 以金字塔图案打印将每个数字放在单独的行上

标签 python python-2.7 printing newline

<分区>

我无法删除 for 循环中的间距,因为生成模式的数字不相同。

我的代码:

for i in range(1,5):
    for j in range(1,i):
       print(j)

产生以下结果:

1
1
2
1
2
3

但我想要的输出是:

1
12
123
1234

最佳答案

试试这个:

print(j, end='')

end 默认为 \n(参见 print() )。另外,一定要在每次外循环迭代结束时打印一个换行符:

for i in range(1,6):  # notice that I changed this to 6
    for j in range(1,i):
        print(j, end='')  # added end=''
    print()  # printing newline here
1
12
123
1234

EDIT I just noticed you were using Python 2.7. Since that's the case, you can use print j, instead of print(j, end='') and print instead of print(). Note that print j, will leave spaces between the js. If you don't want this, you can import sys and use sys.stdout.write(j) instead (see sys).

Furthermore, if you want to use the Python 3 print function as shown above, you can always

from __future__ import print_function

关于python - 以金字塔图案打印将每个数字放在单独的行上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18280905/

相关文章:

python - 如何在查询 Python 中按名称获取字段?

python - 使用列表理解过滤字符串列表

python - 如何在Python中使用列表理解

jquery - css 旋转和对齐

c# - 使用 C# 打印多页 Tiff

java - 打印到文件中

python - REST API POST 请求导致 AttributeError : 'bytes' object has no attribute 'items'

python - 用于时间序列预测的最佳激活函数是什么

Python 每小时计数日志文件

python - 键盘事件未使用 pywin32 发送到窗口