为什么最后不打印hello而是字母都打乱了

问题描述 投票:0回答:1

我正在尝试创建一个效果,使字符串“hello”逐渐出现:

import time

text = "hello"
alphebet = [
    "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o",
    "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"
]
rtext = []
charNum = -1
alpheNum = -1
matching = 0
for char in text:
  charNum += 1
  while matching == 0:
    alpheNum += 1
    rtext.append(alphebet[alpheNum])
    print(*rtext)
    if alphebet[alpheNum] == char:
      matching = 1
    else:
      rtext.remove(rtext[charNum])
    time.sleep(0.2)
  alpheNum = -1
  matching = 0

我试图做到这一点,以便在 for 循环的每次迭代中,对于您尝试显示的文本的每个字母,它们都会遍历每个字母并打印它,直到找到该字母并移至下一个字母。

python arrays python-3.x string list
1个回答
0
投票

您的循环具有比您需要的更多的状态管理。

import time
import sys

text = "hello"
alphabet = [
    "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o",
    "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"
]
rtext = []
for char in text:
    for achar in alphabet:
        print(f"\b{achar}",end="")
        sys.stdout.flush()
        time.sleep(0.2)
        if char == achar:
            print (" ", end="")
            break
print("\b")
© www.soinside.com 2019 - 2024. All rights reserved.