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)?
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
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='')
您可以在循环中编写print(item, end=" ")
。
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.