首页 > 解决方案 > 如何在python中的另外3个引号字符串中嵌套一个条件3个引号字符串?

问题描述

我正在尝试使用 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

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

标签: python-3.xif-statementf-string

解决方案


将来,将您的问题简化为最基本的形式。我不确定我是否理解正确,但我假设您只想打印第 3 行和第 4 行,如果“write_line_3nd4 = True”

将条件放在字符串之外然后将结果附加到里面要简单得多。我已经编辑了你的代码来做到这一点:

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 '')

推荐阅读