python打印格式和换行

时间:2017-10-22 06:45:19

标签: python

我有这个循环:

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)

我在print语句前打破了\,但由于循环意图,它将是额外的标签:

00 year[s] with     interest of 0.05

我发现的唯一解决办法是这样做:

    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)

但它以某种方式破坏了可读性 有没有更好的方法?

4 个答案:

答案 0 :(得分:1)

您可以通过将字符串分解为:

来使用隐式字符串连接
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)

答案 1 :(得分:1)

使用string format并使用方括号()打印Python 3兼容性。如果我们想重复一个字符串,我们也可以使用索引。

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))

或:我们可以使用列表理解并使用换行符连接列表打印项目。

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))

这是打印字符串的非常强大的方法,选项是无穷无尽的,当我浏览文档时,我总是学到新东西。例如,您可以使用它将数字转换为十六进制格式。

rgb = (0,100,200)
string = "#"+"{:02x}"*3
print(string.format(*rgb))

返回:

#0064c8

答案 2 :(得分:0)

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
    ))

避免这种情况的一个好方法是使用字符串格式化功能。你可以用链式格式化它。

答案 3 :(得分:0)

将格式字符串放在循环之外:

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)