I have this loop:
for n in range(101):
money_growth = A*(1 + p/100)**n
print "%d Euro after %3d year[s] with \
interest of %0.2f will be %0.2f" %(A, n, p, money_growth)
I break the line with \ in front of print statement but it will extra tab due to the loop intention:
00 year[s] with interest of 0.05
the only solution I found was doing t this way:
for n in range(101):
money_growth = A*(1 + p/100)**n
print "%d Euro after %3d year[s] with \
interest of %0.2f will be %0.2f" %(A, n, p, money_growth)
but It destroy the readability somehow is there any better way?
4 Answers 4
You may use implicit string concatenation by breaking the string as:
for n in range(101):
money_growth = A*(1 + p/100)**n
print "%d Euro after %3d year[s] with" \
"interest of %0.2f will be %0.2f" %(A, n, p, money_growth)
Comments
Using string format and print with brackets () for Python 3 compitability. We could also use indexes if we want to repeat a string.
A,p,n = 1,1,1
string = "{} Euro after {:>3} year[s] with interest of {} will be {:.2f}"
#string = "{0} Euro after {1:>3} year[s] with interest of {2} will be {3:.2f}"
for n in range(101):
money_growth = A*(1 + p/100)**n
print(string.format(A, n, p, money_growth))
or: we could use list comprehension and join the list print items with row breaks.
A,p,n = 1,1,1
string = "{} Euro after {:>3} year[s] with interest of {} will be {:.2f}"
output = [string.format(A, n, p, A*(1 + p/100)**n) for n in range(101)]
print('\n'.join(output))
This is very powerful way to print strings, the options are endless and I always learn something new when I look through the docs. For instance you can use this to convert numbers to Hex format.
rgb = (0,100,200)
string = "#"+"{:02x}"*3
print(string.format(*rgb))
Returns:
#0064c8
Comments
for n in range(101):
money_growth = A*(1 + p/100)**n
print("{:d} {} {:3d} {} {} {:.2f} {} {:.2f}".format(
A, "Euro after", n, "years[s]","with interest of", p, "will be", money_growth
))
A good way to avoid this is to use string formatting function. You can format it in chain fashion.
Comments
Place the format string outside your loop:
s = "%d Euro after %3d year[s] with interest of %0.2f will be %0.2f"
for n in range(101):
money_growth = A*(1 + p/100)**n
print s % (A,n,p,money_growth)