所以我试图创建一个函数,该函数有一个字符串,末尾有一个数字,可以按顺序倒数。例如:
string =“这是一个测试。” 数字 = [*范围(0, 10)]
这是一个测试。 10 | 10这是一个测试。 9 |这是一个测试。 8 | ...(但我希望这一切都在一行中。)
这是我尝试过的代码:
def comSpeakTimer(speak, seconds):
count = [*range(0, seconds+1)]
numbers = []
timer = []
words = list(speak)
com = []
for i in count:
numbers.append(str(i))
for i in words:
com.append(i)
com.append(' ')
timer.append(numbers[-1])
convo = com + timer
sentence = ''.join(convo)
while len(numbers) != 0:
print(' '*len(sentence), end='\r', flush=True)
time.sleep(1)
numbers.pop()
timer.pop()
timer.append(numbers[-1])
print(sentence, end='\r', flush=True)
time.sleep(1)
但我得到的唯一结果是它会打印 <' '> 然后当它到达“打印(句子)”时,它会一直闪烁“这是一个测试。10 | 这是一个测试。10 | 这是一个测试. 10 | ...”。但奇怪的是,当我将其打印在单独的行上时,它会倒计时:
10 9 8 ...
我不知道我做错了什么。
你可以这样做:
import time
def comSpeakTimer(speak, seconds):
for i in range(seconds+1, 0, -1):
message = speak + ' ' + str(i)
print(message, end='\r', flush=True)
time.sleep(1)
print(' '*len(message), end='\r', flush=True)
comSpeakTimer("this is a test", 10)