0% found this document useful (0 votes)
34 views

Multi Line String With Arguments. How To Declare?: 9 Answers

The document discusses various ways to declare multi-line strings with arguments in Python. It describes using triple quotes to declare a multi-line string and the % formatting operator to include arguments on separate lines. Later responses recommend using the str.format() method and literal string interpolation as cleaner alternatives, especially for strings with many arguments. The discussion concludes that concatenating lines with newlines and parentheses yields source code with consistent indentation while preserving formatting of the printed string.

Uploaded by

vaskore
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
34 views

Multi Line String With Arguments. How To Declare?: 9 Answers

The document discusses various ways to declare multi-line strings with arguments in Python. It describes using triple quotes to declare a multi-line string and the % formatting operator to include arguments on separate lines. Later responses recommend using the str.format() method and literal string interpolation as cleaner alternatives, especially for strings with many arguments. The discussion concludes that concatenating lines with newlines and parentheses yields source code with consistent indentation while preserving formatting of the printed string.

Uploaded by

vaskore
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

8/28/2020 python - Multi line string with arguments. How to declare?

- Stack Overflow

Multi line string with arguments. How to declare?


Asked 8 years, 2 months ago Active 1 year, 3 months ago Viewed 76k times

Let's say I have an extremely long string with arguments that I want to create. I know you can create a multiline
string with

66
cmd = """line 1
line 2
line 3"""

13
But now lets say I want to pass 1, 2, and 3 as arguments.

This works

cmd = """line %d
line %d
line %d""" % (1, 2, 3)

But if I have a super long string with 30+ arguments, how can I possibly pass those arguments in multiple lines?
Passing them in a single line defeats the purpose of even trying to create a multiline string.

Thanks to anyone in advance for their help and insight.

python

edited Jun 15 '18 at 17:12 asked Jun 11 '12 at 18:31


Quillion
5,435 10 50 79

9 Answers Active Oldest Votes

You could abuse the line continuation properties of the parenthesis ( and the comma , .

42 cmd = """line %d
line %d
line %d""" % (
1,
2,
3)

answered Jun 11 '12 at 18:34


Frédéric Hamidi
231k 37 442 452
By using our site, you acknowledge that you have read and understand our Cookie Policy, Privacy Policy, and
our Terms of Service.

https://stackoverflow.com/questions/10985603/multi-line-string-with-arguments-how-to-declare/54564926#54564926 1/10
8/28/2020 python - Multi line string with arguments. How to declare? - Stack Overflow
Thanks so much. Exactly what I was looking for. Never knew I could have multiple lines when using
brackets. This is of great help!!! – Quillion Jun 11 '12 at 20:38

You could use the str.format() function, that allows named arguments, so:

85 '''line {0}
line {1}
line {2}'''.format(1,2,3)

You could of course extend this using Python's *args syntax to allow you to pass in a tuple or list :

args = (1,2,3)
'''line {0}
line {1}
line {2}'''.format(*args)

If you can intelligently name your arguments, the most robust solution (though the most typing-intensive one) would
be to use Python's **kwargs syntax to pass in a dictionary:

args = {'arg1':1, 'arg2':2, 'arg3':3}


'''line {arg1}
line {arg2}
line {arg3}'''.format(**args)

For more information on the str.format() mini-language, go here.

edited Jun 15 '18 at 7:21 answered Jun 11 '12 at 19:22


user8554766 Chinmay Kanchi
51k 21 77 107

1 +1 The **kwargs format is great for readability for many scenarios (though perhaps not the OP's example).
– Casey Kuball Jun 11 '12 at 19:36

The '''string here''' technique is a solid technique, and works well, but it creates some REALLY
UGLY source code when you have to left-align all but the first line and your source code is indented several
levels. To get pretty and easy-to-look-at source code with nice alignment, therefore, use my technique here
instead: stackoverflow.com/a/54564926/4561887. It has its drawbacks, of course, but for anything less than
a long paragraph of text, I like this other technique over using the ''' ''' technique. – Gabriel Staples
Feb 7 '19 at 1:16

Check out this self-documenting docstring printing, as module documentation, which uses the type of
technique you present above. I just added it to the bottom of my answer here:
stackoverflow.com/a/54564926/4561887. – Gabriel Staples May 22 '19 at 0:55

If you have curly braces in your string, escape them by using double curly braces: {{ and }} – LoMaPh Oct 2
'19 at 2:23

By usingThe
our easiest way
site, you might be to use
acknowledge that literal stringread
you have interpolation (available
and understand from
our Python
Cookie 3.6 ,onwards
Policy Privacy and assuming
Policy, and all the
arguments are
our Terms of Service. in scope).

https://stackoverflow.com/questions/10985603/multi-line-string-with-arguments-how-to-declare/54564926#54564926 2/10
8/28/2020 python - Multi line string with arguments. How to declare? - Stack Overflow

18 cmd = f"""line {1}


line {2}
line {3}"""

answered Aug 23 '17 at 10:48


Michael Mauderer
3,141 1 19 45

thanks but this doesn't work well in the situation that the original string contains a lot of brackets – Luk Aron
Aug 5 at 23:08

One more variant with the string.format()-Function.

16 s = "{0} " \
"{1} " \
"{2}" \
.format("Hello", "world", "from a multiline string")
print(s)

edited Aug 23 '17 at 10:41 answered Aug 23 '17 at 8:31


elim
966 1 12 15

As @Chinmay Kanchi says, you can do:

5 '''line {0}
line {1}
line {2}'''.format(1,2,3)

However, I think it looks goofy with alignment that has to be full-left-aligned on new lines, especially when you are
doing this already several levels indented, so I'd prefer it to be written more like this:

'''line {0}
line {1}
line {2}'''.format(1,2,3)

That works, BUT IS WRONG! It interprets all spaces to the left of line {1} and line {2} as real spaces, so
printing it will look goofy:

1
2
3

By usingInstead
our site,ofyou acknowledge that you have read and understand our Cookie Policy, Privacy Policy, and
our Terms of Service.

https://stackoverflow.com/questions/10985603/multi-line-string-with-arguments-how-to-declare/54564926#54564926 3/10
8/28/2020 python - Multi line string with arguments. How to declare? - Stack Overflow

1
2
3

So, a work-around is to use the + operator to concatenate, and parenthesis around the concatenated
string, as well as explicit new-line ( \n ) characters, like this:

('line {0}\n' +
'line {1}\n' +
'line {2}').format(1,2,3)

Perfect (in my opinion)! Now it looks nice and aligned in both the source code and the actual string if you print it.

Full example:
UGLY Source Code!

num1 = 7
num2 = 100
num3 = 75.49

# Get some levels of indentation to really show the effect well.


# THIS IS *UGLY*! Notice the weird forced-left-align thing for the string I want to print!
if (True):
if (True):
if (True):
# AAAAAH! This is hard to look at!
print('''num1 = {}
num2 = {}
num3 = {}'''.format(num1, num2, num3))

# More lines of code go here


# etc
# etc

Output:

num1 = 7
num2 = 100
num3 = 75.49

Pretty Example! Ahh, so nice to look at in the source code. :)


This is what I prefer.

# Get some levels of indentation to really show the effect well.


if (True):
if (True):
if (True):
# IMPORTANT: the extra set of parenthesis to tie all of the concatenated strings
together here is *required*!
By using our site, you acknowledge that you have read and understand our Cookie Policy, Privacy Policy, and
print(('num1 = {}\n' +
our Terms of Service. 'num2 = {}\n' +

https://stackoverflow.com/questions/10985603/multi-line-string-with-arguments-how-to-declare/54564926#54564926 4/10
8/28/2020 python - Multi line string with arguments. How to declare? - Stack Overflow
'num3 = {}')
.format(num1, num2, num3))

# More lines of code go here


# etc
# etc

Output:

num1 = 7
num2 = 100
num3 = 75.49

Update 21 May 2019: Sometimes the "ugly" multi-line string


really is the best way to go!
So, I've been using Python to auto-generate C header and source (.h/.c) files from text-based configuration
files, and after doing a fair amount of this I've concluded that the benefits of simply copy-pasting large chunks of
text from a configuration file into my Python script outweigh any "ugliness" factors.

Therefore, I've determined that the following is my preferred way to do it when a large, multi-line copy-pasted string
is required, for example:

Option 1:
- Use parenthesis around the whole long string to allow the opening """ to be on a new line

# Get some levels of indentation to still show the "ugliness" effect.


if (True):
if (True):
if (True):
header = (
"""
/*
my custom file header info here
*/

#pragma once

#include "{}"

const {} {};
""").format(include, struct_t, struct)

print("header =" + header)

Option 2:
- No parenthesis, but still put the closing """ on its own line

# Get some levels of indentation to still show the "ugliness" effect.


if (True):
if (True):
if acknowledge
By using our site, you (True): that you have read and understand our Cookie Policy, Privacy Policy, and
header = """
our Terms of Service.
/*
https://stackoverflow.com/questions/10985603/multi-line-string-with-arguments-how-to-declare/54564926#54564926 5/10
8/28/2020 python - Multi line string with arguments. How to declare? - Stack Overflow
my custom file header info here
*/

#pragma once

#include "{}"

const {} {};
""".format(include, struct_t, struct)

print("header =" + header)

Option 3:
- No parenthesis around the whole string, and put the closing """ on the same line as the string contents to
prevent adding a (potentially undesirable) \n at the end.
- However, put the remainder of format( on a new line (or on many new lines) in case it is long.

# Get some levels of indentation to still show the "ugliness" effect.


if (True):
if (True):
if (True):
header = """
/*
my custom file header info here
*/

#pragma once

#include "{}"

const {} {};""".format(
include, struct_t, struct) # indentation here can literally be *anything*, but I like to
indent 1 level; since it's inside parenthesis, however, it doesn't matter

print("header =" + header)

Output:

Options 1 and 2 produce an exactly identical output, with an extra \n at the very end of the string, which is
ok in most cases

Option 3 produces the same exact output as Options 1 and 2 except that it does not have the extra \n at the
very end of the string, in case that is undesirable for your case

Whether you use Option 1, 2, or 3 really doesn't matter--it's just user preference at this point, other than the
extra \n as noted just above

This is what is printed by Options 1, 2, and 3 above:

/*
my custom file header info here
*/

#pragma once

By using our site, you acknowledge


#include that you have read and understand our Cookie Policy, Privacy Policy, and
"<stdint.h>"
our Terms of Service.

https://stackoverflow.com/questions/10985603/multi-line-string-with-arguments-how-to-declare/54564926#54564926 6/10
8/28/2020 python - Multi line string with arguments. How to declare? - Stack Overflow

const my_struct_t my_struct;

PUTTING IT ALL TOGETHER: a mix of the "pretty" and


"ugly" methods together to get the best result in this demo
of printing docstring documentation for your module!
Here's a basic example of using both the "pretty" and the "ugly" multi-line string methods presented above in order
to get the best benefits of each. This also shows how to use and print module "docstrings" to document your
module. Notice how the """ -based multi-line technique gives us great spacing because the way I've done it below
there is an automatic newline ( \n ) after the opening """ and before the closing """ since that's how the string
is written.

# PRETTY, AND GOOD.


print("\n\n" +
"########################\n" +
"PRINT DOCSTRING DEMO:\n" +
"########################")

import sys

def printDocstrings():
"""
Print all document strings for this module, then exit.
Params: NA
Returns: NA
"""

# A LITTLE BIT UGLY, BUT GOOD! THIS WORKS GREAT HERE!


print("""
---------------------
Module Documentation:
---------------------
printDocstrings:{}
myFunc1:{}
class Math:{}
__init__:{}
add:{}
subtract:{}""".format(
printDocstrings.__doc__,
myFunc1.__doc__,
Math.__doc__,
Math.__init__.__doc__,
Math.add.__doc__,
Math.subtract.__doc__))

sys.exit()

def myFunc1():
"""
Do something.
Params: NA

Output:
By using-our site,how
Notice youpretty
acknowledge that you have
and well-formatted read and understand
it all automatically is, as the our Cookie
tabs, Policy
newlines, , Privacy
and spacingPolicy , and
of your docstrings
our Terms
areofall
Service .
automatically preserved when you print them this way!

https://stackoverflow.com/questions/10985603/multi-line-string-with-arguments-how-to-declare/54564926#54564926 7/10
8/28/2020 python - Multi line string with arguments. How to declare? - Stack Overflow

########################
PRINT DOCSTRING DEMO:
########################

---------------------
Module Documentation:
---------------------
printDocstrings:
Print all document strings for this module, then exit.
Params: NA
Returns: NA

myFunc1:
Do something.
Params: NA
Returns: NA

class Math:
A basic "math" class to add and subtract

__init__:
New object initialization function.
Params: NA
Returns: NA

add:
Add a and b together.
Params: a 1st number to add
b 2nd number to add
Returns: the sum of a + b

subtract:
Subtract b from a.
Params: a number to subtract from
b number to subtract
Returns: the result of a - b

References:
1. Python docstrings: https://www.geeksforgeeks.org/python-docstrings/

Note: you can also use the help() method to access a module or class's documentation (but in an
interactive manner), as shown in the link above, like this:

help(Math) # to interactively display Class docstring


help(Math.add) # to interactively display method's docstring

edited May 22 '19 at 1:25 answered Feb 7 '19 at 1:08


Gabriel Staples
6,852 3 46 76

To have the arguments in the same line they are inserted, you could do it like this:
By using our site, you acknowledge that you have read and understand our Cookie Policy, Privacy Policy, and
our Terms of Service.

https://stackoverflow.com/questions/10985603/multi-line-string-with-arguments-how-to-declare/54564926#54564926 8/10
8/28/2020 python - Multi line string with arguments. How to declare? - Stack Overflow

4 cmd = "line %d\n"%1 +\


"line %d\n"%2 +\
"line %d\n"%3

[EDIT:] In reply to the first comment I came up with this:

cmd = "\n".join([
"line %d"%1,
"line %d"%2,
"line %d"%3])

answered Jun 11 '12 at 18:38


Qlaus
847 4 14

Doing that with 30+ arguments would not be very efficient. "".join() on a list, on the other hand... :) –
Frédéric Hamidi Jun 11 '12 at 18:40

This works for me:

2 cmd = """line %d
line %d
line %d""" % (
1,
2,
3
)

answered Jun 11 '12 at 18:34


Cameron
81.4k 18 171 213

You may use textwrap.dedent to remove leading spaces from lines:

2 import textwrap

cmd = str.strip(textwrap.dedent(
'''
line {}
line with indent
line {}
line {}
'''
.format(1, 2, 3)))

This results in:


By using our site, you acknowledge that you have read and understand our Cookie Policy, Privacy Policy, and
our Terms of Service.

https://stackoverflow.com/questions/10985603/multi-line-string-with-arguments-how-to-declare/54564926#54564926 9/10
8/28/2020 python - Multi line string with arguments. How to declare? - Stack Overflow

line 1
line with indent
line 2
line 3

answered Mar 15 '19 at 15:55


George Sovetov
3,437 3 21 50

Please vote, those who use PyCharm: youtrack.jetbrains.com/issue/PY-34646. What the auto-formatting
does and the formatting check rules are not consistent in the snippet in the question. – George Sovetov
Sep 6 '19 at 14:39

Here is the simplest version, which is also IDE-friendly in terms of checking format arguments:

1 cmd = (
'line {}\n'
'line {}\n'
'line {}\n'
.format(1, 2, 3))

Multiline arguments version:

cmd = (
'line {}\n'
'line {}\n'
'line {}\n'
.format(
'very very very very very very very very very long 1',
'very very very very very very very very very long 2',
'very very very very very very very very very long 3',
)
)

edited Mar 15 '19 at 15:56 answered Mar 15 '19 at 15:50


George Sovetov
3,437 3 21 50

Please vote, those who use who use PyCharm and hanging closing brackets:
youtrack.jetbrains.com/issue/PY-35059 – George Sovetov Sep 6 '19 at 14:36

Please vote, those who use PyCharm: youtrack.jetbrains.com/issue/PY-34646. The auto-formatting and the
formatting check are not consistent in the snippet in the question. – George Sovetov Sep 6 '19 at 14:38

By using our site, you acknowledge that you have read and understand our Cookie Policy, Privacy Policy, and
our Terms of Service.

https://stackoverflow.com/questions/10985603/multi-line-string-with-arguments-how-to-declare/54564926#54564926 10/10

You might also like