How do I create a multiline Python string with inline variables?

前端 未结 7 2058
耶瑟儿~
耶瑟儿~ 2020-12-07 08:47

I am looking for a clean way to use variables within a multiline Python string. Say I wanted to do the following:

string1 = go
string2 = now
string3 = great
         


        
7条回答
  •  孤城傲影
    2020-12-07 09:24

    f-strings, also called “formatted string literals,” are string literals that have an f at the beginning; and curly braces containing expressions that will be replaced with their values.

    f-strings are evaluated at runtime.

    So your code can be re-written as:

    string1="go"
    string2="now"
    string3="great"
    print(f"""
    I will {string1} there
    I will go {string2}
    {string3}
    """)
    

    And this will evaluate to:

    I will go there
    I will go now
    great
    

    You can learn more about it here.

提交回复
热议问题