0

I am trying to a paragraph of lines using 3 quote strings where some group of lines in the paragraph are to be included on a if condition. I am using {} brackets for those conditional lines and since each of them have to be on the next line, I have to use 3 quote strings for them. So its a nested 3 quote string with a condition

For example, I have

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

It gives me an error as such:

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

How do use conditional multi-line strings inside multi-line strings?

Harshad Surdi
  • 23
  • 1
  • 6

2 Answers2

0

In the future, simplify your question down to the most basic form. I am not sure if I understand you correctly but I am assuming you only want to print your line 3 and line 4 if "write_line_3nd4 = True"

It is much simpler to put your conditional outside of the string and then append the result inside. I have edited your code to do this:

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

EDIT: If you insist on putting your conditionals inside your multi-line string, you could do it using inline expressions. This is what it would look like:

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 '')
Purin
  • 56
  • 9
  • Sorry for the complicating the question, I'm sort of new to stackexchange. I can't use condition outside the string because the actual paragraph I'm writing is huge with large number of conditional multi-line sections in it, so it would be a nightmare to keep track of all the conditions outside the main 3 quote string. Is there any better way? – Harshad Surdi May 29 '19 at 18:38
  • Got it thanks! I am using a bit modified version of this like, ...+ (f''' x=3,4''' if write_line_3nd4 == True else ''") – Harshad Surdi May 29 '19 at 19:47
0

Maybe this will help.

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)

Im not sure what you're asking either but this is my guess as to what you are looking for.