如何在列表中创建带有 f-string 的新行?

huangapple go评论66阅读模式
英文:

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

问题

lst.append(f"第一行变量是 {var}{NL}第二行 {NL}")
lst.append(f"第三行{NL}第四行变量是 {var}")
英文:

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?

答案1

得分: 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)

输出:

test
new line
first line var is xyz
a second line 

third line
forth line var is xyz
英文:

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

huangapple
  • 本文由 发表于 2023年5月21日 01:49:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/76296613.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定