0

I am trying to use f-string within a list. I have created a new line variable. Standard variables work fine but the new line variable does not

NL = '\n'
var = 'xyz'
lst = []
print(f'test{NL}new line')
lst.append(f"first line var is {var}{NL}a second line {NL}")
lst.append(f"third line{NL}forth line var is {var}")
print(lst)

creates the output

test
new line
['first line var is xyz\na second line \n', 'third line\nforth line var is xyz']

How can I do this?

wjandrea
  • 28,235
  • 9
  • 60
  • 81
Mick Sulley
  • 99
  • 2
  • 11

1 Answers1

5

It's working fine

When a list is printed, strings in the list are shown raw, not printed. If you print the strings one by one, you will see that they print as expected:

NL = '\n'
var = 'xyz'
lst = []
print(f'test{NL}new line')
lst.append(f"first line var is {var}{NL}a second line {NL}")
lst.append(f"third line{NL}forth line var is {var}")
for s in lst:
    print(s)

Output:

test
new line
first line var is xyz
a second line 

third line
forth line var is xyz
wjandrea
  • 28,235
  • 9
  • 60
  • 81