如何在列表中创建 f 字符串新行?

Mic*_*ley 0 python f-string

我正在尝试在列表中使用 f 字符串。我创建了一个新的行变量。标准变量工作正常,但新行变量不行

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)
Run Code Online (Sandbox Code Playgroud)

创建输出

test
new line
['first line var is xyz\na second line \n', 'third line\nforth line var is xyz']
Run Code Online (Sandbox Code Playgroud)

我怎样才能做到这一点?

The*_*ine 5

工作正常

打印列表时,列表中的字符串将显示为原始字符串,而不是打印出来。如果您一一打印字符串,您将看到它们按预期打印:

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)
Run Code Online (Sandbox Code Playgroud)

输出:

test
new line
first line var is xyz
a second line 

third line
forth line var is xyz
Run Code Online (Sandbox Code Playgroud)