我正在尝试使用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
如何在多行字符串中使用条件多行字符串?
答案 0 :(得分:0)
将来,将您的问题简化为最基本的形式。我不确定我是否理解正确,但我假设如果“ 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
编辑:如果您坚持将条件放在多行字符串中,则可以使用内联表达式来实现。看起来像这样:
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 '')
答案 1 :(得分:0)
也许这会有所帮助。
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)
我不确定您要问的是什么,但这是我对要寻找的东西的猜测。