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

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

    NOTE: The recommended way to do string formatting in Python is to use format(), as outlined in the accepted answer. I'm preserving this answer as an example of the C-style syntax that's also supported.

    # NOTE: format() is a better choice!
    string1 = "go"
    string2 = "now"
    string3 = "great"
    
    s = """
    I will %s there
    I will go %s
    %s
    """ % (string1, string2, string3)
    
    print(s)
    

    Some reading:

    • String formatting
    • PEP 3101 -- Advanced String Formatting

提交回复
热议问题