Nested f-strings

后端 未结 6 2013
礼貌的吻别
礼貌的吻别 2020-11-30 07:10

Thanks to David Beazley\'s tweet, I\'ve recently found out that the new Python 3.6 f-strings can also be nested:

>>> price = 478.23
>>> f\"         


        
6条回答
  •  情书的邮戳
    2020-11-30 07:54

    Working on a pet project I got sidetracked by writing my own DB library. One thing I discovered was this:

    >>> x = dict(a = 1, b = 2, d = 3)
    >>> z = f"""
        UPDATE TABLE 
            bar 
        SET 
            {", ".join([ f'{k} = ?'     for k in x.keys() ])} """.strip()
    >>> z
    'UPDATE TABLE 
        bar 
    SET 
        a = ?, b = ?, d = ?  '
    

    I was also surprised by this and honestly I am not sure I would ever do something like this in production code BUT I have also said I wouldn't do a lot of other things in production code.

提交回复
热议问题