简体   繁体   English

带管道的单线输出

[英]Single-line output with pipe

Really basic question but I just couldn't get it to work, currently I have a list, header:非常基本的问题,但我无法让它工作,目前我有一个列表,标题:

    header = [
        'Name', 'EmojiXpress, mil.', 'Instagram, mil.', 'Twitter, mil.'
]

I want a final output of:我想要一个最终输出:

| Name | EmojiXpress, mil. | Instagram, mil. | Twitter, mil. |

My current code looks like:我当前的代码如下所示:

for name in header:
    print('|', end='')    

    print(name, end='')

    print('|', end='')

But this results in:但这导致:

|Name||EmojiXpress, mil.||Instagram, mil.||Twitter, mil.|

Please help, thank you.请帮忙,谢谢。

print(f'| {" | ".join(header)} |')

Output:输出:

| Name | EmojiXpress, mil. | Instagram, mil. | Twitter, mil. |

join() will join the elements of a list by the string you specify beforehand. join()将通过您预先指定的字符串连接列表的元素。 Adding in f-strings or formatted strings, we can attach the |添加f-strings或格式化字符串,我们可以附加| to the beginning and end of the string as well.到字符串的开头和结尾也是如此。

This is happening because you are printing both an opening and a closing pipe for each item.发生这种情况是因为您正在为每个项目打印一个开口和一个关闭管道。 My solution is printing an opening pipe for each item in the loop, and then printing a closing pipe after the loop is over.我的解决方案是为循环中的每个项目打印一个打开的管道,然后在循环结束后打印一个关闭的管道。

Try this..尝试这个..

for name in header:
    print(' | ', end='')    
    print(name, end='')
print(' | ')

Result:结果:

| Name | EmojiXpress, mil. | Instagram, mil. | Twitter, mil. | 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM