0

Basically, I'm doing iterative calculations over time, and the precision of the time values I want outputted over each loop pass can vary depending on my predefined parameters. Let's say I used this as my predefined time step:

tstep = 0.5 # seconds

So I would like outputted:

iteration 1:   time = 0.0 s
iteration 2:   time = 0.5 s
iteration 3:   time = 1.0 s

And so on. But, let's say I switch my timestep:

tstep = 0.25 # seconds

Now I would want for following output:

iteration 1: time = 0.00 s
iteration 2: time = 0.25 s
iteration 3: time = 0.50 s

And so on. Here is what I would intuitively would think could work:

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

But this doesn't work. Does anyone have a possible solution to this? Possibly an alternate way of formatting that I'm just not considering? I prefer not to use %g simply because the output isn't as clean. Thanks in advance!

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
fuGGet321
  • 83
  • 5
  • 1
    use `.format`, `%` -style formatting is *old* and not very full featured. Better yet, use Python 3.6 and use f-strings... – juanpa.arrivillaga Oct 23 '17 at 17:42
  • `%`-style formatting lets you set the width with the `*` parameter. It is rather limited, but it works. The duplicate shows how, *and* shows you the more flexible `str.format()` method. – Martijn Pieters Oct 23 '17 at 17:44
  • @MartijnPieters Thank you !! That's exactly what I was looking for. I apologize for the duplicate, but I couldn't find that one on my own. – fuGGet321 Oct 23 '17 at 18:54

1 Answers1

-1

Use this: print 'iteration ', count+1,': time=',t,'s'

imacoder
  • 166
  • 1
  • 11