英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论