如何根据计数器调整输出的制表符?

1 投票
3 回答
2253 浏览
提问于 2025-04-17 11:17

我想打印一句话大约十次(具体次数由range()决定),但是我希望第一句缩进一次,第二句缩进两次,以此类推...

这是我的代码:

count = 0

for i in range(10):
    print("\t*countPython is fun")
    count += 1

现在我得到的输出如下,这并不是我想要的:

*countPython is fun
*countPython is fun
*countPython is fun
*countPython is fun
*countPython is fun
*countPython is fun
*countPython is fun

我知道这应该在print()函数里处理,但我不太明白怎么做。请问我该如何解决这个问题呢?

3 个回答

1

在Python 3中,print()函数可以接收用逗号分隔的多个参数,然后会用默认的空格' '来分隔这些参数进行打印。

for i in range(1, 11):
    print('\t' * i, 'Py3 has a great print function!') 

或者

for i in range(1, 11):
    #removes space after tab(s) 
    print('\t' * i, 'Py3 has a great print function!', sep='') 
1

正如julio.alegria在你的问题中提到的,range()这个函数可以让你不需要额外的计数器了:

for i in range(10):
    print(('\t' * (i + 1)) + 'Python is fun')
9

* count 必须放在字符串外面:

for i in range(10):
    print(("\t"*count) + "Python is fun")
    count += 1

撰写回答