Search code examples
pythonf-string

How to create f-string new line within a list?


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?


Solution

  • 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