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

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

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

问题

  1. lst.append(f"第一行变量是 {var}{NL}第二行 {NL}")
  2. 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

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

creates the output

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

How can I do this?

答案1

得分: 5

它运行正常

当打印列表时,列表中的字符串会以原始形式显示,而不会被打印出来。如果逐个打印字符串,您会看到它们按预期打印出来:

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

输出:

  1. test
  2. new line
  3. first line var is xyz
  4. a second line
  5. third line
  6. 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:

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

Output:

  1. test
  2. new line
  3. first line var is xyz
  4. a second line
  5. third line
  6. 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:

确定