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

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

    This is what you want:

    >>> string1 = "go"
    >>> string2 = "now"
    >>> string3 = "great"
    >>> mystring = """
    ... I will {string1} there
    ... I will go {string2}
    ... {string3}
    ... """
    >>> locals()
    {'__builtins__': , 'string3': 'great', '__package__': None, 'mystring': "\nI will {string1} there\nI will go {string2}\n{string3}\n", '__name__': '__main__', 'string2': 'now', '__doc__': None, 'string1': 'go'}
    >>> print(mystring.format(**locals()))
    
    I will go there
    I will go now
    great
    

提交回复
热议问题