Unpythonic way of printing variables in Python?

前端 未结 5 1998
时光取名叫无心
时光取名叫无心 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")
    
    0 讨论(0)
  • 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)    
    
    0 讨论(0)
  • 2021-01-02 17:40

    The answer is, no, the syntax for strings in Python does not include variable substitution inthe style of Perl (or Ruby, for that matter). Using … % locals() is about as slick as you are going to get.

    0 讨论(0)
  • 2021-01-02 17:43

    Using % locals() or .format(**locals()) is not always a good idea. As example, it could be a possible security risk if the string is pulled from a localization database or could contain user input, and it mixes program logic and translation, as you will have to take care of the strings used in the program.

    A good workaround is to limit the strings available. As example, I have a program that keeps some informations about a file. All data entities have a dictionary like this one:

    myfile.info = {'name': "My Verbose File Name", 
                   'source': "My Verbose File Source" }
    

    Then, when the files are processes, I can do something like this:

    for current_file in files:
        print 'Processing "{name}" (from: {source}) ...'.format(**currentfile.info)
        # ...
    
    0 讨论(0)
  • 2021-01-02 17:47

    Since Python 3.6, you could have what you wanted.

    >>> name = "world"
    >>> print(f'hello {name}')
    hello world
    

    note the string prefix f above

    0 讨论(0)
提交回复
热议问题