Hướng dẫn format multiline string python

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

Nội dung chính

  • Variables in a multi-line string
  • Variables in a lengthy single-line string
  • Not the answer you're looking for? Browse other questions tagged python string variables multiline or ask your own question.
  • How do you add a variable to a multiline string in Python?
  • How do you assign multiple lines to a variable in Python?
  • How do you encode a multiline string in Python?
  • What is a multiline string Python?

Nội dung chính

  • Variables in a multi-line string
  • Variables in a lengthy single-line string
  • Not the answer you're looking for? Browse other questions tagged python string variables multiline or ask your own question.
  • How do you add a variable to a multiline string in Python?
  • How do you assign multiple lines to a variable in Python?
  • How do you encode a multiline string in Python?
  • What is a multiline string Python?
string1 = go
string2 = now
string3 = great

"""
I will $string1 there
I will go $string2
$string3
"""

I'm looking to see if there is something similar to $ in Perl to indicate a variable in the Python syntax.

If not - what is the cleanest way to create a multiline string with variables?

Stevoisiak

21.1k24 gold badges117 silver badges206 bronze badges

asked Apr 11, 2012 at 19:28

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.

user2357112

241k26 gold badges392 silver badges467 bronze badges

answered Apr 11, 2012 at 19:32

Simeon VisserSimeon Visser

115k18 gold badges175 silver badges177 bronze badges

7

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

Stevoisiak

21.1k24 gold badges117 silver badges206 bronze badges

answered Apr 11, 2012 at 19:32

David CainDavid Cain

15.6k11 gold badges66 silver badges73 bronze badges

3

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}."""

answered Oct 30, 2017 at 20:15

StevoisiakStevoisiak

21.1k24 gold badges117 silver badges206 bronze badges

4

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.

answered Jun 28, 2020 at 8:39

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

answered Apr 11, 2012 at 19:43

HavokHavok

5,6061 gold badge35 silver badges43 bronze badges

2

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

Stevoisiak

21.1k24 gold badges117 silver badges206 bronze badges

answered Sep 18, 2015 at 7:52

jesterjunkjesterjunk

2,24419 silver badges17 bronze badges

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: "{{", "}}"

answered Jun 28, 2020 at 4:28

Not the answer you're looking for? Browse other questions tagged python string variables multiline or ask your own question.

How do you add a variable to a multiline string in Python?

Python Program to Create a Long Multiline String.

my_string = '''The only way to learn to program is by writing code.''' print[my_string] ... .

my_string = ["The only way to \n" "learn to program is \n" "by writing code."] print[my_string].

How do you assign multiple lines to a variable in Python?

Use triple quotes to create a multiline string It is the simplest method to let a long string split into different lines. You will need to enclose it with a pair of Triple quotes, one at the start and second in the end. Anything inside the enclosing Triple quotes will become part of one multiline string.

How do you encode a multiline string in Python?

Python Multiline String gives better readability. Three single quotes, three double quotes, brackets, and backslash can be used to create multiline strings. Whereas the user needs to mention the use of spaces between the strings.

What is a multiline string Python?

A multiline string in Python begins and ends with either three single quotes or three double quotes. Any quotes, tabs, or newlines in between the “triple quotes” are considered part of the string. Python's indentation rules for blocks do not apply to lines inside a multiline string.

Chủ Đề