Using locals() and format() method for strings: are there any caveats?

前端 未结 3 1100
傲寒
傲寒 2020-12-29 01:04

Are there any disadvantages, caveats or bad practice warnings about using the following pattern?

def buildString(user, name = \'john\', age=22):
    userId =         


        
3条回答
  •  梦毁少年i
    2020-12-29 01:55

    There is now an official way to do this, as of Python 3.6.0: formatted string literals.

    It works like this:

    f'normal string text {local_variable_name}'
    

    E.g. instead of these:

    "hello %(name)s you are %(age)s years old" % locals()
    "hello {name}s you are {age}s years old".format(**locals())
    "hello {name}s you are {age}s years old".format(name=name, age=age)
    

    just do this:

    f"hello {name}s you are {age}s years old"
    

    Here's the official example:

    >>> name = "Fred"
    >>> f"He said his name is {name}."
    'He said his name is Fred.'
    >>> width = 10
    >>> precision = 4
    >>> value = decimal.Decimal("12.34567")
    >>> f"result: {value:{width}.{precision}}"  # nested fields
    'result:      12.35'
    

    Reference:

    • Python 3.6 What's New
    • PEP 498
    • Lexical analysis description

提交回复
热议问题