Unpythonic way of printing variables in Python?

前端 未结 5 2020
时光取名叫无心
时光取名叫无心 2021-01-02 16:51

Someone has recently demonstrated to me that we can print variables in Python like how Perl does.

Instead of:

print(\"%s, %s, %s\" % (foo, bar, baz))         


        
5条回答
  •  无人及你
    2021-01-02 17:20

    I prefer the .format() method myself, but you can always do:

    age = 99
    name = "bobby"
    print name, "is", age, "years old"
    

    Produces: bobby is 99 years old. Notice the implicit spaces.

    Or, you can get real nasty:

    def p(*args):
        print "".join(str(x) for x in args))
    
    p(name, " is ", age, " years old")
    

提交回复
热议问题