简体   繁体   中英

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:

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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