Multi Line String With Arguments. How To Declare?: 9 Answers
Multi Line String With Arguments. How To Declare?: 9 Answers
- Stack Overflow
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.
python
You could abuse the line continuation properties of the parenthesis ( and the comma , .
42 cmd = """line %d
line %d
line %d""" % (
1,
2,
3)
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:
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
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
16 s = "{0} " \
"{1} " \
"{2}" \
.format("Hello", "world", "from a multiline string")
print(s)
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
Output:
num1 = 7
num2 = 100
num3 = 75.49
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))
Output:
num1 = 7
num2 = 100
num3 = 75.49
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
#pragma once
#include "{}"
const {} {};
""").format(include, struct_t, struct)
Option 2:
- No parenthesis, but still put the closing """ on its own line
#pragma once
#include "{}"
const {} {};
""".format(include, struct_t, struct)
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.
#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
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
/*
my custom file header info here
*/
#pragma once
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
import sys
def printDocstrings():
"""
Print all document strings for this module, then exit.
Params: NA
Returns: NA
"""
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:
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
cmd = "\n".join([
"line %d"%1,
"line %d"%2,
"line %d"%3])
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
2 cmd = """line %d
line %d
line %d""" % (
1,
2,
3
)
2 import textwrap
cmd = str.strip(textwrap.dedent(
'''
line {}
line with indent
line {}
line {}
'''
.format(1, 2, 3)))
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
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))
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',
)
)
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