如何在 python 中将条件 3 引号字符串嵌套在另一个 3 引号字符串中?

How to nest a conditional 3 quote strings inside another 3 quote strings in python?

我正在尝试使用 3 个引号字符串来处理一段行,其中段落中的一些行组将包含在 if 条件下。我在这些条件行中使用了 {} 括号,并且由于它们中的每一个都必须在下一行中,所以我必须为它们使用 3 个引号字符串。所以它是一个带有条件

的嵌套 3 引号字符串

比如我有

write_line_3nd4 = True
paragraph = f'''
this is line one
x = 12 #line two
{f'''
line 3,4 #this is line 3
x=34 #this is line 4''' if write_line_3nd4 else ''}
'''

它给我这样的错误:

File "<ipython-input-36-4bcb98c8ebe0>", line 6
line 3,4 #this is line 3
     ^
SyntaxError: invalid syntax

如何在多行字符串中使用条件多行字符串?

以后,将您的问题简化为最基本的形式。我不确定我是否理解正确,但我假设您只想在 "write_line_3nd4 = True"

时打印第 3 行和第 4 行

将条件放在字符串外面然后将结果附加到里面要简单得多。我已经编辑了您的代码来执行此操作:

write_line_3nd4 = True

if write_line_3nd4 == True:
    line3 = '3,4'
    line4 = 'x=34'
else:
    line3 = ''
    line4 = ''

paragraph = f'''
this is line one
x = 12
''' + line3 + '''
''' + line4

编辑:如果您坚持将条件放在 multi-line 字符串中,您可以使用内联表达式来完成。这就是它的样子:

write_line_3nd4 = True
paragraph = f'''
this is line one
x = 12
''' + ('3,4' if write_line_3nd4 == True else '') + '''
''' + ('x=34' if write_line_3nd4 == True else '')

也许这会有所帮助。

x = "one"
if x == "one":
    y = "two"
else:
    y = "three"
print("""
    This is some line of printed text
    This is some line of printed more text
    these {} and {} are variables designated by `str.format()`
    """.format(x, y))
print(x)

我也不确定你在问什么,但这是我对你在寻找什么的猜测。