What is print(f“…”)

后端 未结 4 1091
梦毁少年i
梦毁少年i 2020-12-09 04:33

I am reading through a python script that takes an input of XML files and outputs an XML file. However, I do not understand the printing syntax. Can someone please explain w

4条回答
  •  一个人的身影
    2020-12-09 05:24

    In Python 3.6, the f-string was introduced(PEP 498). In short, it is a way to format your string that is more readable and fast.

    Example:

    agent_name = 'James Bond'
    kill_count = 9
    
    # old ways
    print('{0} has killed {1} enemies '.format(agent_name,kill_count))
    
    # f-strings way
    print(f'{agent_name} has killed {kill_count} enemies')
    

    The f or F in front of strings tell Python to look at the values inside {} and substitute them with the variables values if exists. The best thing about the is that you can do cool stuff in {}, e.g. {kill_count * 100}.

    Readings:

    • PEP 498 Literal String Interpolation
    • Python String Formatting

提交回复
热议问题