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

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

    The common way is the format() function:

    >>> s = "This is an {example} with {vars}".format(vars="variables", example="example")
    >>> s
    'This is an example with variables'
    

    It works fine with a multi-line format string:

    >>> s = '''\
    ... This is a {length} example.
    ... Here is a {ordinal} line.\
    ... '''.format(length='multi-line', ordinal='second')
    >>> print(s)
    This is a multi-line example.
    Here is a second line.
    

    You can also pass a dictionary with variables:

    >>> d = { 'vars': "variables", 'example': "example" }
    >>> s = "This is an {example} with {vars}"
    >>> s.format(**d)
    'This is an example with variables'
    

    The closest thing to what you asked (in terms of syntax) are template strings. For example:

    >>> from string import Template
    >>> t = Template("This is an $example with $vars")
    >>> t.substitute({ 'example': "example", 'vars': "variables"})
    'This is an example with variables'
    

    I should add though that the format() function is more common because it's readily available and it does not require an import line.

    0 讨论(0)
  • 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
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-07 09:30

    If anyone came here from python-graphql client looking for a solution to pass an object as variable here's what I used:

    query = """
    {{
      pairs(block: {block} first: 200, orderBy: trackedReserveETH, orderDirection: desc) {{
        id
        txCount
        reserveUSD
        trackedReserveETH
        volumeUSD
      }}
    }}
    """.format(block=''.join(['{number: ', str(block), '}']))
    
     query = gql(query)
    

    Make sure to escape all curly braces like I did: "{{", "}}"

    0 讨论(0)
  • 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__': <module '__builtin__' (built-in)>, '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
    
    0 讨论(0)
  • 2020-12-07 09:35

    A dictionary can be passed to format(), each key name will become a variable for each associated value.

    dict = {'string1': 'go',
            'string2': 'now',
            'string3': 'great'}
    
    multiline_string = '''I'm will {string1} there
    I will go {string2}
    {string3}'''.format(**dict)
    
    print(multiline_string)
    


    Also a list can be passed to format(), the index number of each value will be used as variables in this case.

    list = ['go',
            'now',
            'great']
    
    multiline_string = '''I'm will {0} there
    I will go {1}
    {2}'''.format(*list)
    
    print(multiline_string)
    


    Both solutions above will output the same:

    I'm will go there
    I will go now
    great

    0 讨论(0)
提交回复
热议问题