用循环建立单词

2024-06-09 01:52:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试为类创建一个使用python的程序,其工作方式如下:

'Enter a word: " (EG Stack)

然后输出

S
St
Sta
Stac
Stack

我相信它会使用循环功能,但我完全卡住了!你知道吗


Tags: 程序功能stack方式wordstentereg
3条回答

http://pastebin.com/CDzNfdbJ 明白了,我不太明白,但它很管用。你知道吗

msg = raw_input("Enter a word: ") #raw_input will convert the input into a string 
                                  #otherwise it would crash without quotation marks

word = ""                         #Initialize a variable

for letter in msg:                #Cycle through each letter
   word += letter                 #Adds that letter to your string
   print(word)                    #Prints out the current letters

您可以使用切片来实现输出。for循环的每次迭代都会增加一个索引变量(i),这用于显示字符串中不断增加的片段。你知道吗

>>> word = 'Stack'
>>> for i in range(1, len(word)+1):
...     print word[:i]
... 
S
St
Sta
Stac
Stack

>>> word='Slicing'
>>> for i in range(1, len(word)+1):
...     print word[:i]
... 
S
Sl
Sli
Slic
Slici
Slicin
Slicing

您可以阅读Pythontutorial中关于切片的内容。你知道吗

相关问题 更多 >