Python:运行程序以反转任何给定单词的顺序

时间:2019-07-08 09:59:51

标签: python loops

我正在尝试用Python创建一个程序,该程序接受所有输入的单词并颠倒顺序,并以相反的顺序打印单词。但是我没有得到预期的结果。这是我正在使用的代码:

myString = input("Enter any String: ")
length = len(myString)-1
reverse = []
i = 0
while length>=0:
    reverse.append(myString[length])
    length -=1

while length<0:
    break
print(reverse)
reverseString = ''
j = 0
while j<=length:
    reverseString +=reverse[j]
    j+=1
while j> length:
    break
print(reverseString)

在输出中,我仅看到以下内容:

Enter any String: De Costa
['a', 't', 's', 'o', 'C', ' ', 'e', 'D']

而不是预期的:' atsoC eD '

我要去哪里错了?

3 个答案:

答案 0 :(得分:1)

这是因为您的长度变量在第一个循环中递减后就变为0,因此reverseString的循环永远不会运行,所以reverseString始终具有值”,您必须重新初始化length变量才能使循环运行。为此,请在length = len(myString)-1下添加reverseString = ''

或者简单地说

myString = input("Enter any String: ")
length = len(myString)-1
reverse = []
i = 0

while length>=0:
    reverse.append(myString[length])
    length -=1

while length<0:
    break
print(reverse)

reverseString = ''
length = len(myString)-1

j = 0
while j<=length:
    reverseString +=reverse[j]
    j+=1
while j> length:
    break
print(reverseString)

答案 1 :(得分:0)

# using loop
def reverse(s):
  str = ""
  for i in s:
    str = i + str
  return str

print (reverse("Hello World")) # dlroW olleH

# using recursion
def reverse1(s):
    if len(s) == 0:
        return s
    else:
        return reverse(s[1:]) + s[0]

print (reverse1("Hello World")) # dlroW olleH

# using extended slice syntax
def reverse2(string):
    string = string[::-1]
    return string

print (reverse2("Hello World")) # dlroW olleH


# using reversed()
def reverse3(string):
    string = "".join(reversed(string))
    return string

print (reverse3("Hello World")) # dlroW olleH

答案 2 :(得分:0)

您可以使用索引切片。.我认为下面的代码很有用。

myString = input("Enter any String: ")
reverse = ""
reverse = myString[::-1]