Py学习  »  Python

如何在python中通过逐字打印和反向打印字符串

skribbsta • 4 年前 • 1084 次点击  

E、 g-单词是: string

g
gn
gni
gnir
gnirt
gnirts

我希望用户能够输入任何单词,而不仅仅是“String”

我试过的代码:

text = input('Enter a string: ')
reversed_text = ''
last_index = len(text) - 1
for i in range(last_index, -1, -5):
  for i in range(last_index, -1, -1):
    for i in range(last_index, -1, -1):

      reversed_text += text[i]
      print(reversed_text)
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/55270
 
1084 次点击  
文章 [ 4 ]  |  最新文章 4 年前
Michael Ruth
Reply   •   1 楼
Michael Ruth    4 年前

此解决方案使用扩展切片来反转词段并用空格分隔每个词段。其他答案用换行符分隔了相反的词段。只是替换 ' '.join 具有 '\n'.join

word = 'string'
reversed = '\n'.join(word[-1:i:-1] for i in range(-2, -2 - len(word), -1))
print(reversed)

编辑

skribbsta
Reply   •   2 楼
skribbsta    4 年前
s=input("Word: ")
r=''
for char in reversed(s):
    r+=char
    print(r)

print ("Reversed word is %s " % (r))

这是我使用的代码,它起作用了谢谢你的回答

FishingCode
Reply   •   3 楼
FishingCode    4 年前

使用用户输入进行此操作的一个简单方法应该是:

newstring = "" 
enterString = (str(input("Enter a string to be reversed:")))
count = 0
for i in reversed(enterString): 
   newstring += i
   count += 1
   print ("Reversed string %s is this: %s" % (count, newstring))

输出,计数直到最后一个字符的次数:

 Enter a string to be reversed:hello
 Reversed string 1 is this: o
 Reversed string 2 is this: ol
 Reversed string 3 is this: oll
 Reversed string 4 is this: olle
 Reversed string 5 is this: olleh
Juan Sebastian Prieto Bustaman
Reply   •   4 楼
Juan Sebastian Prieto Bustaman    4 年前
s='string'
r=''
for char in reversed(s):
    r+=char
    print(r)

这段代码按你的要求执行。