简体   繁体   English

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

[英]How to print a string by printing letter by letter and in reverse in python

I want to print a string in reverse and build it by printing letter by letter.我想反向打印一个字符串并通过一个字母一个字母的打印来构建它。

Eg - Word is: string例如 - 单词是: string

Ideal output is:理想的输出是:

g
gn
gni
gnir
gnirt
gnirts

I want the user to be able to enter any word not just "String"我希望用户能够输入任何单词而不仅仅是“字符串”

Code I have tried:我试过的代码:

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)
s=input("Word: ")
r=''
for char in reversed(s):
    r+=char
    print(r)

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

This is the code I used, it works thank you for the answers这是我使用的代码,它有效,谢谢您的回答

s='string'
r=''
for char in reversed(s):
    r+=char
    print(r)

This code does what you're asking.此代码执行您的要求。

A simple way of doing this with user input should be something on these lines:使用用户输入执行此操作的简单方法应该是以下几行:

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))

Output with count of how many times till it gets the last character:输出有多少次直到它得到最后一个字符:

 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

This solution uses extended slice to reverse the word segments and separate each with a space.该解决方案使用扩展切片来反转单词段并用空格分隔每个段。 Other answers have separated the reversed word segments with a newline.其他答案用换行符分隔了反向词段。 Just replace ' '.join with '\\n'.join if you require this behavior.如果您需要此行为,只需将' '.join替换为'\\n'.join

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

edit : Separated reversed word segments with newline to reflect updated question.编辑:用换行符分隔反向词段以反映更新的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM