如何在python中使用for循环向反向字符串添加字母

2024-06-13 03:28:05 发布

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

我是python编码的初学者。我希望我的输出是: 例1:

Word: hello #hello is the input
o
ol
oll
olle
olleh

例2:

Word: nice # nice is the input
e
ec
eci
ecin

基本上,它是向后编码的,但它显示每个字母都被添加了。 到目前为止,我的代码是:

text = input("Words: ")
reserved_text = text[::-1]
print(reserved_text)
-------------output----
Words: Nice
eciN

我不知道如何使用for循环来获得整个反转单词之前的步骤


Tags: thetexthello编码inputiswordnice
2条回答

好像是学校的榜样。但我想你不是在这里试图简单地得到一个评分练习的解决方案;)

也就是说:您可能需要使用for循环

text = input("Words: ")
for i in range(1,len(text)+1):
  print(text[::-1][:i:])

由于python中的字符串是不可变的,因此必须使用辅助字符串来获得所需的输出。也必须使用“反转”

s = input ("Words: ")

s_rev = ""

for n in reversed(s):
    s_rev = s_rev + n
    print s_rev

相关问题 更多 >