Dariusz Mydlarz
Dariusz Mydlarz

Reputation: 3002

Python. One line for loop printer with format

What is the best way to achieve something like this

items = ['a', 'b', 'c']
print("Items:")
for i in items:
    print("\t", i)

in one line statement? This does not do what I want, because is adding tabulator only between items, not in front of every one:

print("\n\t".join(items))

I want output to look like this:

Items:
    a
    b
    c

Upvotes: 0

Views: 58

Answers (3)

tktk
tktk

Reputation: 11734

You can always patch items so that \n\t would appear at the beginning as well: So if

print("\n\t".join(items))

results in

a\n\tb\n\tc

This

print("\n\t".join([''] + items))

results in

\n\ta\n\tb\n\tc

or

items = ['', 'a', 'b', 'c']
print("\n\t".join(items))

Upvotes: 0

Vincent Beltman
Vincent Beltman

Reputation: 2114

This works for me:

print("Items:\n\t" + "\n\t".join(['a', 'b', 'c']))

Or this i you prefer a for loop:

print "Items:"
for i in ['a', 'b', 'c']: print "\t" + i

Upvotes: 2

Vishnu Upadhyay
Vishnu Upadhyay

Reputation: 5061

you can use print function.

>>> items = ['a', 'b', 'c']
>>> print ('\t', *items, sep='\t')
        a   b   c

Upvotes: 0

Related Questions