【问题标题】:Checking in a string from the last character to the first one检入从最后一个字符到第一个字符的字符串
【发布时间】:2019-08-10 23:31:01
【问题描述】:

我想在 python 中使用 while 循环检查从最后一个字符到第一个字符的字符串。

Linux - Ubuntu - 我正在使用 Atom 文本编辑器。

fruit = 'banana'
letter = fruit[5]
length = len(fruit)
index = 5

    while index > len(fruit):
            letter = fruit[index]
            print(letter)
            index = index - 1

终端正确列出了字符,但这样做了两次,最后显示超出范围错误。检查:

a
n
a
n
a
b
a
n
a
n
a
b
Traceback (most recent call last):
  File "youtube.py", line 5, in <module>
    letter = fruit[index]
IndexError: string index out of range

【问题讨论】:

标签: python


【解决方案1】:

由于您的索引从 5 开始并向下移动,请将您的测试更改为 index &gt;= 0

fruit = 'banana'
letter = fruit[5]
index = 5

while index >= 0:
    letter = fruit[index]
    print(letter)
    index = index - 1

【讨论】:

  • 嗯,当然,但如果你想让它工作,也可以将 length 设置为 len(fruit) - 1
  • @hugo length 未使用。可以删除。
  • 你是对的,我的错。还在写index = len(fruit) - 1会更好吗? (但我知道您的目标不是过多地更改原始代码)
【解决方案2】:

谢谢大家,我尝试了以下方法,它成功了。我使用了中断功能。

fruit = 'banana'
index = 0
while index < len(fruit) :
    letter = fruit[index - 1]
    print(letter)
    index = index - 1
    if index == -6 :
        break

【讨论】:

    【解决方案3】:

    这里有一些方法

    • 反向切片

      fruit = 'banana'
      for f in fruits[::-1]:
         print(f)
      
    • reversed 内置

      fruit = 'banana'
      for f in reversed(fruits):
         print(f)   
      
    • while循环

      fruit = 'banana'
      fruit_len = len(fruit)
      while fruit_len:
          fruit_len -=1
          print(fruit[fruit_len])
      

    【讨论】:

      【解决方案4】:

      我试过了,效果很好:

      index = 0
      fruit = "apple"
          while index < len(fruit):
          index = index - 1
              if index < -(len(fruit)):
                  break
          letter = fruit[index]
          print(letter)
          
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-01-07
        • 2013-11-26
        • 2011-04-11
        • 1970-01-01
        • 2017-10-30
        • 2022-11-01
        • 2018-12-03
        相关资源
        最近更新 更多