python-3.x - 如何在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
如何在多行字符串中使用条件多行字符串?
解决方案
将来,将您的问题简化为最基本的形式。我不确定我是否理解正确,但我假设您只想打印第 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 '')
推荐阅读
- excel - Excel 每天自动刷新并将文件保存到我的电脑中
- r - 根据预定义向量和离散结果中的数据创建变量
- php - Laravel:根据会话变量显示或隐藏内容
- c - 为什么程序不适用于数组,但当它是普通变量时可以正常工作?
- php - 从 RS232 读取并发送命令 trought php url
- python - 如何在 PsychoPy 中使用同一个键多次翻转?
- hibernate - 为什么使用字符串解析日期在 Hibernate 中找不到结果
- javascript - 不推荐使用可观察的“of”。什么是等价物?
- sas - 我有一种方法可以在 SAS 日志中自定义“显示宏变量值”的快捷方式
- c# - 如何将值分配给数组中的随机位置?