FateCoreUloom
FateCoreUloom

Reputation: 463

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.

Upvotes: 0

Views: 117

Answers (2)

this
this

Reputation: 351

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. | 

Upvotes: 1

PacketLoss
PacketLoss

Reputation: 5746

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. Adding in f-strings or formatted strings, we can attach the | to the beginning and end of the string as well.

Upvotes: 4

Related Questions