如何在python中将输入的文本反转?

2024-06-16 12:50:29 发布

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

我试着写一个程序,从输入的字母中构造新词,反之亦然

#    vise    versa    
print    ("word vise versa")
word = input("Input your text ")
new_word = ""
while word:
    position = len(word) - 1
    for letter in word:
    new_word += letter[position]
    position -= 1
print(new_word)        

总是有错误

 Traceback (most recent call last):
 File "4_2.py", line 9, in <module>
      new_word += letter[position]
 IndexError: string index out of range

我做错了什么? 谢谢!你知道吗


Tags: textin程序newinputyour字母position
3条回答

首先,在您的代码中,如果您的输入不是None或False值,那么您的循环将永远运行,因为word不是False值。你知道吗

第二,可以使用字符串的反向切片或如下所示的列表:

#    vise    versa    
print("word vise versa")
word = raw_input("Input your text ")
new_word = ""
if word:
  new_word = word[::-1]
print(new_word)
  1. 使用raw_input方法从用户处获取输入字
  2. 通过len方法获取输入字的长度。你知道吗
  3. 使用while循环在新变量中添加字符。你知道吗
  4. 将长度变量递减1

    print "Program: word vise versa"
    word = raw_input("Input your text:")
    new_word = ""
    wdlen = len(word)
    while wdlen:
        new_word += word[wdlen-1]
        wdlen -= 1
    
    print new_word
    

输出:

$ python test.py 
Program: word vise versa
Input your text:abcdef
fedcba

使用slice。你知道吗

更多信息https://docs.python.org/2/whatsnew/2.3.html#extended-slices

>>> a = "12345"
>>> a[::-1]
'54321'

问题可能是你在下面几行所做的

for letter in word:
    new_word += letter[position]

其中字母是单词中的每个字母,如果单词是abc,则首先是“a”,然后是“b”,然后是“c”。在seconds字符串上,您试图使用字母“a”作为数组,这是不好的。您可能希望偏移到单词数组中?你知道吗

相关问题 更多 >