扩展本章的秒表项目,让它利用 rjust()和 ljust()字符串方法来“美化”的输出。 (这些方法在第 6 章中介绍过)。输出不是像这样:
而是这样
请注意,对于 lapNum、lapTime 和 totalTime 等整型和浮点型变量,你需要字符 串版本,以便对它们调用字符串方法。接下来,利用第 6 章中介绍的 pyperclip 模块, 将文本输出复制到剪贴板,以便用户可以将输出快速粘贴到一个文本文件或电子邮 件中。
#! python3
# stopwatch.py - A simple stopwatch program.
#本题只需在原来的秒表程序上稍加修改即可,具体输出形式可能略有不同
import time,pyperclip
# Display the program's instructions.
print('Press enter to begin. Afterwards, press ENTER to "click" the stopwatch. Press Ctrl-C to quit.')
input() # press Enter to begin
print('Started.')
startTime = time.time() # get the first lap's start time
lastTime = startTime
lapNum = 1
L=[]
# Start tracking the lap times.
try:
while True:
input()
lapTime = round(time.time() - lastTime, 2)
totalTime = round(time.time() - startTime, 2)
#输出的结果result
result='Lap #%s:%s ( %s)' % (str(lapNum).rjust(3), str(totalTime).rjust(6), str(lapTime).ljust(5))
print(result,end='')
L.append(result)#将结果添加到列表中
lapNum += 1
lastTime = time.time() # reset the last lap time
except KeyboardInterrupt:
# Handle the Ctrl-C exception to keep its error message from displaying.
print('\nDone.')
pyperclip.copy('\n'.join(L))#将结果存放到剪贴板中