【发布时间】:2017-10-23 17:39:41
【问题描述】:
基本上,我会随着时间的推移进行迭代计算,并且我希望在每个循环传递中输出的时间值的精度可能会根据我的预定义参数而有所不同。假设我使用它作为我预定义的时间步:
tstep = 0.5 # seconds
所以我想输出:
iteration 1: time = 0.0 s
iteration 2: time = 0.5 s
iteration 3: time = 1.0 s
等等。但是,假设我改变了我的时间步:
tstep = 0.25 # seconds
现在我想要以下输出:
iteration 1: time = 0.00 s
iteration 2: time = 0.25 s
iteration 3: time = 0.50 s
等等。以下是我直觉认为可行的方法:
dec = len(str(tstep)[(str(tstep).find('.')+1):]) # Decimal places defined in tstep variable
t = 0.
count = 1
while t <= 5.:
print 'iteration %d: time = %.%d%f' % (count, dec, t)
t += tstep
count += 1
但这不起作用。有没有人对此有可能的解决方案?可能是我不考虑的另一种格式化方式?我不喜欢使用%g,只是因为输出不那么干净。提前致谢!
【问题讨论】:
-
使用
.format,%- 样式格式是旧的 并且功能不是很全。更好的是,使用 Python 3.6 并使用 f-strings... -
%样式格式允许您使用*参数设置宽度。它相当有限,但它有效。副本展示了和如何向您展示更灵活的str.format()方法。 -
@MartijnPieters 谢谢!!这正是我一直在寻找的。我为重复道歉,但我自己找不到那个。
标签: python python-2.7 printing format