Unpythonic way of printing variables in Python?

前端 未结 5 2024
时光取名叫无心
时光取名叫无心 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:38

    The only other way would be to use the Python 2.6+/3.x .format() method for string formatting:

    # dict must be passed by reference to .format()
    print("{foo}, {bar}, {baz}").format(**locals()) 
    

    Or referencing specific variables by name:

    # Python 2.6
    print("{0}, {1}, {2}").format(foo, bar, baz) 
    
    # Python 2.7/3.1+
    print("{}, {}, {}").format(foo, bar, baz)    
    

提交回复
热议问题