假设我有一个非常长的字符串,其中包含我想要创建的参数。 我知道你可以使用
创建一个多行字符串cmd = """line 1
line 2
line 3"""
但现在我想说我想传递1,2和3作为参数。
这有效
cmd = """line %d
line %d
line %d""" % (1, 2, 3)
但是如果我有一个包含30多个参数的超长字符串,我怎么能在多行中传递这些参数呢?将它们传递到一行就会破坏甚至尝试创建多行字符串的目的。
感谢任何人提前寻求他们的帮助和见解。
答案 0 :(得分:67)
您可以使用允许命名参数的str.format()
函数,因此:
'''line {0}
line {1}
line {2}'''.format(1,2,3)
您当然可以使用Python的*args
语法对其进行扩展,以便传入tuple
或list
:
args = (1,2,3)
'''line {0}
line {1}
line {2}'''.format(*args)
如果您可以智能地命名您的参数,那么最强大的解决方案(尽管键入密集程度最高)将使用Python的**kwargs
语法传入字典:
args = {'arg1':1, 'arg2':2, 'arg3':3}
'''line {arg1}
line {arg2}
line {arg3}'''.format(**args)
有关str.format()
迷你语言的详细信息,请转到here。
答案 1 :(得分:29)
您可以滥用括号(
和逗号,
的续行属性。
cmd = """line %d
line %d
line %d""" % (
1,
2,
3)
答案 2 :(得分:8)
使用string.format()的另一个变体 - Function。
{{1}}
答案 3 :(得分:6)
最简单的方法可能是使用literal string interpolation(从Python 3.6开始提供并假设所有参数都在范围内)。
cmd = f"""line {1}
line {2}
line {3}"""
答案 4 :(得分:3)
要将参数插入到同一行,您可以这样做:
cmd = "line %d\n"%1 +\
"line %d\n"%2 +\
"line %d\n"%3
[编辑:]在回复第一条评论时,我提出了这个问题:
cmd = "\n".join([
"line %d"%1,
"line %d"%2,
"line %d"%3])
答案 5 :(得分:2)
这对我有用:
cmd = """line %d
line %d
line %d""" % (
1,
2,
3
)
答案 6 :(得分:2)
作为@Chinmay Kanchi says,您可以执行以下操作:
'''line {0}
line {1}
line {2}'''.format(1,2,3)
但是,我认为它看起来有点愚蠢,必须在新行上完全左对齐,尤其是当您执行此操作时,已经缩进了多个级别,因此我更喜欢这样写: / p>
'''line {0}
line {1}
line {2}'''.format(1,2,3)
那行得通,但错误!它将line {1}
和line {2}
左侧的所有空格都解释为真实空格,因此打印时看起来会很愚蠢:
1
2
3
代替
1
2
3
因此,一种解决方法是使用+
运算符进行连接,并在连接的字符串和显式换行(\n
)字符周围加括号,例如:
('line {0}\n' +
'line {1}\n' +
'line {2}').format(1,2,3)
完美(我认为)!现在,如果您将其打印出来,它看起来很好,而且在源代码和实际字符串中都对齐。
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
输出:
num1 = 7
num2 = 100
num3 = 75.49
这就是我想要的。
# 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*!
print(('num1 = {}\n' +
'num2 = {}\n' +
'num3 = {}')
.format(num1, num2, num3))
# More lines of code go here
# etc
# etc
输出:
num1 = 7
num2 = 100
num3 = 75.49
因此,我一直在使用Python从基于文本的配置文件中自动生成C头文件和源(.h / .c)文件,在做了很多这些之后,得出的结论是,简单地将配置文件中的大块文本复制粘贴到我的Python脚本中的好处胜过任何“丑陋”因素。
因此,我确定,当需要较大的多行复制粘贴字符串时,例如,以下是我的首选处理方法:
选项1:
-在整个长字符串周围使用括号,以使开头"""
换行
# 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)
选项2:
-没有括号,但仍将结束"""
放在自己的行上
# 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)
选项3:
-在整个字符串周围不要加上括号,并在字符串的内容的最后一行加上结束"""
,以防止在末尾添加{(1)}(可能是不希望的)。
-但是,如果很长,请将\n
的其余部分放在新行(或许多新行)上。
format(
输出:
# 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)
,在大多数情况下都是可以的\n
,以防您不满意\n
这是上面选项1、2和3打印的内容:
\n
这是同时使用上面介绍的“漂亮”和“丑陋”多行字符串方法以获取每种方法的最大好处的基本示例。这也显示了如何使用和打印模块“文档字符串”来记录模块。请注意,基于/*
my custom file header info here
*/
#pragma once
#include "<stdint.h>"
const my_struct_t my_struct;
的多行技术如何为我们提供了很大的间距,因为在打开"""
之后且在{{1}关闭\n
,因为这就是写字符串的方式。
"""
输出:
-请注意,这一切都是多么漂亮和合理,因为以这种方式打印它们时,它们的选项卡,换行符和文档字符串的间距都将自动保留!
"""
Python文档字符串:https://www.geeksforgeeks.org/python-docstrings/
注意:您也可以使用help()
方法访问模块或类的文档(但以交互方式 ),如上面的链接所示,就像这样:
# 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
Returns: NA
"""
pass
class Math:
"""
A basic "math" class to add and subtract
"""
def __init__(self):
"""
New object initialization function.
Params: NA
Returns: NA
"""
pass
def add(a, b):
"""
Add a and b together.
Params: a 1st number to add
b 2nd number to add
Returns: the sum of a + b
"""
return a + b
def subtract(a, b):
"""
Subtract b from a.
Params: a number to subtract from
b number to subtract
Returns: the result of a - b
"""
return a - b
printDocstrings()
答案 7 :(得分:1)
上周,我几乎不了解Python textwrap
module,它具有非常方便的textwrap.dedent()
功能,考虑到it's been around since Python 2.7,我不敢相信它并不流行!
在多行字符串周围使用textwrap.dedent()
解决了my previous answer的所有问题!
Here's the official documentation on it(强调):
textwrap.dedent(text)
从文本的每一行中删除所有常见的前导空白。
这可用于使三引号字符串与显示的左边缘对齐,同时仍将它们以缩进形式显示在源代码中。
请注意,制表符和空格都被视为空白,但它们并不相等:行
" hello"
和"\thello"
被认为没有共同的前导空白。仅包含空格的行在输入中被忽略,并在输出中标准化为单个换行符。
例如:
def test(): # end first line with \ to avoid the empty line! s = '''\ hello world ''' print(repr(s)) # prints ' hello\n world\n ' print(repr(dedent(s))) # prints 'hello\n world\n'
因此,而不是像the most-upvoted answer states(这样会丢失漂亮,简洁的缩进):
cmd = '''line {0}
line {1}
line {2}'''.format(1,2,3)
print(cmd)
执行此操作(并保留漂亮,干净的缩进)!
cmd = textwrap.dedent('''\
line {0}
line {1}
line {2}''').format(1,2,3)
print(cmd)
当然,如果它真的很长,您也可以将每个format()
arg也放在新行上:
cmd = textwrap.dedent('''\
line {0}
line {1}
line {2}
line {3}
line {4}
line {5}
line {6}
line {7}
line {8}
line {9}
line {10}
line {11}
line {12}
line {13}
line {14}
line {15}
line {16}
line {17}
line {18}
line {19}''').format(
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11,
12,
13,
14,
15,
16,
17,
18,
19,
20,
)
print(cmd)
as I stated in my original answer(保留缩进的外观,但使用起来有点乏味)代替了:
print("\n\n" +
"########################\n" +
"PRINT DOCSTRING DEMO:\n" +
"########################")
...您现在可以执行此操作!-使我的多行字符串在打印时“与显示的左边缘对齐,同时仍以缩进形式在源代码中显示它们”:
# Note: use the `\` below to prevent the implicit newline right after it from being printed.
print(textwrap.dedent("""
########################
PRINT DOCSTRING DEMO:
########################\
"""))
除了这个,它中间还有一些难看的缩进:
def printDocstrings1():
"""
Print all document strings for this module, then exit.
Params: NA
Returns: NA
"""
# A LITTLE BIT UGLY, BUT IT WORKS.
print("""
---------------------
Module Documentation:
---------------------
printDocstrings:{}
myFunc1:{}
class Math:{}
__init__:{}
add:{}
subtract:{}""".format(
printDocstrings1.__doc__,
myFunc1.__doc__,
Math.__doc__,
Math.__init__.__doc__,
Math.add.__doc__,
Math.subtract.__doc__))
...执行此操作,该操作使用textwrap.dedent()
来保持缩进效果!:
def printDocstrings2():
"""
Print all document strings for this module, then exit.
Params: NA
Returns: NA
"""
# MUCH CLEANER! Now I can have the proper indentation on the left withOUT
# it printing that indentation!
print(textwrap.dedent("""\
---------------------
Module Documentation:
---------------------
printDocstrings:{}
myFunc1:{}
class Math:{}
__init__:{}
add:{}
subtract:{}""").format(
printDocstrings2.__doc__,
myFunc1.__doc__,
Math.__doc__,
Math.__init__.__doc__,
Math.add.__doc__,
Math.subtract.__doc__))
您可以在eRCaGuy_hello_world的textwrap_practice_1.py GitHub存储库中运行上面的测试代码。
答案 8 :(得分:0)
这是最简单的版本,就检查format
参数而言,它也是IDE友好的:
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',
)
)
答案 9 :(得分:0)
您可以使用textwrap.dedent
从行中删除前导空格:
import textwrap
cmd = str.strip(textwrap.dedent(
'''
line {}
line with indent
line {}
line {}
'''
.format(1, 2, 3)))
结果是:
line 1
line with indent
line 2
line 3