python - 格式正确的乘法表

如何制作一个整齐的乘法表?我当前的代码是:

n=int(input('Please enter a positive integer between 1 and 15: '))
for row in range(1,n+1):
    for col in range(1,n+1):
        print(row*col)
    print()

这正确地将所有内容相乘,但以列表形式显示。我知道我需要正确地嵌套它并留出空间,但我不确定它在哪里?

最佳答案

快速方式(不过可能水平空间太大):

n=int(input('Please enter a positive integer between 1 and 15: '))
for row in range(1,n+1):
    for col in range(1,n+1):
        print(row*col, end="\t")
    print()

更好的方法:

n=int(input('Please enter a positive integer between 1 and 15: '))
for row in range(1,n+1):
    print(*("{:3}".format(row*col) for col in range(1, n+1)))

并使用 f-strings (Python3.6+)

for row in range(1, n + 1):
    print(*(f"{row*col:3}" for col in range(1, n + 1)))

https://stackoverflow.com/questions/20415384/

相关文章:

python - .format() 使用 {0 :g} to remove trailing ze

python - 在 python 日志记录中是否有一个格式化程序来截断字符串?

html - 如何使用 CSS 自动添加节号(1.2、3.4.1)?

Python - 为字符串格式化运算符解包列表的简短方法?

c# - DateTime.ToString 格式

python - 使用其 API 和 Python 在 Google 表格电子表格中设置单元格格式

python - 带有 float 的格式字符串中的千位分隔符

python - python - 如何使用单行将列表/元组转换为python中的空格分隔字符串?

input - AngularJs:如何在输入中格式化数据?

android - PhoneNumberFormattingTextWatcher 不工作