按递减长度打印字符串

0 投票
2 回答
516 浏览
提问于 2025-05-10 22:58

我刚开始学Python,所以请多多包涵。

我想得到以下的输出:

输入:apple

输出:

apple
appl
app
ap
a

我尝试过的:

b = raw_input("Enter the String")
for n in reversed(range(len(b)-1):
    print b[0:n]

我在for循环中遇到了语法错误。需要帮助。

相关文章:

  • 暂无相关问题
暂无标签

2 个回答

3

你在你的 for 循环的末尾缺少一个必要的 ) 符号。

for n in reversed(range(len(b)-1)): #<- two parenthesis before the colon
3

你可以使用负数索引,这样就不需要反转字符串了。

b = raw_input("Enter the String")
print b 
for i in range(1, len(b)):
    print b[:-i]

撰写回答