简体   繁体   English

试图调整,居中和调整秒表的输出

[英]Trying to ljust, center, and rjust output of stopwatch

I have a stopwatch program that is fully functional. 我有一个功能齐全的秒表程序。 All I am trying to do is format the output to be aligned. 我要做的就是格式化输出以使其对齐。

This was a section of the code before trying to edit: 在尝试编辑之前,这是代码的一部分:

 lapTime = round(time.time() - lastTime, 2)
 totalTime = round(time.time() - startTime, 2)
 print ('Lap #%s: %s (%s)' % (lapNum, totalTime, lapTime), end='')

This was one of the attempts to align the output: 这是对齐输出的尝试之一:

 print ('Lap ', lapNum.ljust(10, ' ')), ':',totalTime.center(20, ' '), 
 lapTime.rjust(30, ' '))

I am getting the error: 我收到错误消息:

 File "D:/stopwatch2.py", line 19, in main
     print ('Lap ' + str(lapNum.ljust(10, ' ')), ':',totalTime.center(40, 
 ' '), lapTime.rjust(50, ' '))
 AttributeError: 'int' object has no attribute 'ljust'

ljust and center are string methods. ljustcenter是字符串方法。 You have to convert the value to strings before you call those methods: 在调用这些方法之前,必须将值转换为字符串:

print ('Lap ', str(lapNum).ljust(10, ' '), ':', str(totalTime).center(20, ' '))

You can also use str.format and the format options : 您还可以使用str.formatformat选项

print ('Lap {:<10}: {:=20}'.format(lapNum, totalTime))
# output: Lap 1         :           1557332386

With str.format the conversion to a string is implicit. 使用str.format ,隐式转换为字符串。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM