[英]Program to output letter pyramid
To print the output 打印输出
A
A B
A B C
A B C D
A B C D E
I used the following code, but it does not work correctly. 我使用了以下代码,但它无法正常工作。
strg = "A B C D E F"
i = 0
while i < len(strg):
print strg[0:i+1]
print "\n"
i = i + 1
For this code the obtained output is: 对于此代码,获得的输出是:
A
A
A B
A B
A B C
A B C
A B C D
A B C D
A B C D E
A B C D E
A B C D E F
Why does each line get printed twice? 为什么每行打印两次?
Whitespace. 空白。 You need to increment
i
by 2 instead of 1. Try: 您需要将
i
递增2而不是1.尝试:
strg = "A B C D E F"
i = 0
while i < len(strg):
print strg[0:i+2]
print "\n"
i = i+2
This will allow you to skip over the whitespace as "indices" of the string 这将允许您跳过空格作为字符串的“索引”
A little more pythonic: 多一点pythonic:
>>> strg = "ABCDEF"
>>> for index,_ in enumerate(strg):
print " ".join(strg[:index+1])
A
A B
A B C
A B C D
A B C D E
A B C D E F
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.