Reputation: 13
items=['a', 'b', 'c', 'd', 'e']
print("The first 3 items in the list are: ")
for item in items[:3]:
print(item)
#or
print("The first 3 items in the list are: " + str(items[:3]))
Q: How should I make the output of the 'first 3 items' to be horizontal(like the second code) but without the square brackets(like the 1st code)?
Upvotes: 1
Views: 329
Reputation: 10920
You can use str.join(iterable)
, where str
is the separator between the items in the iterable
. For example:
items = ['a', 'b', 'c', 'd', 'e']
print('The first 3 items in the list are: ' + ', '.join(items[:3]))
This prints:
The first 3 items in the list are: a, b, c
In this case, ', '
is the separator between the items of the list. You can change it according to your needs. For example, using ' '.join(items[:3])
instead would result in:
The first 3 items in the list are: a b c
Upvotes: 2
Reputation: 380
There are several ways. The appropriate here (IMO) is to use
print("items are: " + ', '.join(items[:3]))
Which (depending on your python version) can be simplified to:
print(f'items are: {", ".join(items[:3])}')
or without the comma
Another way is to tell the print
to not print linebreaks:
for item in items[:3]:
print(item, end='')
Upvotes: 0
Reputation: 5385
This would do it:
print("The first 3 items in the list are: " + str(items[:3])[1:-1])
assuming you don't mind the items separated by commas.
Upvotes: 0