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

前端 未结 7 2023
耶瑟儿~
耶瑟儿~ 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:39

    You can use Python 3.6's f-strings for variables inside multi-line or lengthy single-line strings. You can manually specify newline characters using \n.

    Variables in a multi-line string

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

    I will go there
    I will go now
    great

    Variables in a lengthy single-line string

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

    I will go there. I will go now. great.


    Alternatively, you can also create a multiline f-string with triple quotes.

    multiline_string = f"""I will {string1} there.
    I will go {string2}.
    {string3}."""
    
    0 讨论(0)
提交回复
热议问题