简体   繁体   English

Python:使用格式字符串时打印多行

[英]Python: print multi-lines when using format string

When I try to print multi-lines with format string in python, the bash show the error like that: 当我尝试在python中使用格式字符串打印多行时,bash显示如下错误:

a = 'tony'
b = '20'
print ("I am %s\n"+
       "I am %s years old\n"
       % (a,b))

TypeError: not all arguments converted during string formatting TypeError:在字符串格式化期间并非所有参数都已转换

I'm wondering what's wrong with that and what's the right way to use format string to print multi-lines. 我想知道这是怎么回事,以及使用格式字符串打印多行的正确方法是什么。


if i write code like this, it'll output correctly. 如果我写这样的代码,它将正确输出。 However, the single line code will be too long, that's not what I want. 但是,单行代码将太长,这不是我想要的。

print ("I am %s\nI am %s years old\n" % (a,b))

You need line continuation here, use \\ 您需要在此处line continuation ,使用\\

Try this : 尝试这个 :

a = 'tony'
b = '20'
print("I am %s\n" \
      "I am %s years old\n" \
       % (a,b))

I am tony
I am 20 years old

or you can just remove + 或者您可以删除+

print("I am %s\n"
      "I am %s years old\n"
       % (a,b))

I am tony
I am 20 years old

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

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