Today, I was asked to write a small python code to print out all items in a list with comma seperated. The last item would end the with a ‘dot’, or full stop.
For example, here is a list of sports:
sports = [ 'basketball', 'soccer', 'netball' ]
And I was asked to print out the expected output:
My favourite sports are: basketball, soccer, netball.
But how do I do this? Today, I’ll be showing you how to show the expected output using join and without join.
Display items in the list with join
The first one I’ll be showing you is where I will use a function called join.
Before we start, just a little knowledge of what join is. Join is a function that takes all the elements of a list or tuple and jons them into a single string. It will return the joined string. To use join, you have to specify a string separator that will be used to seperate the concatenated string.
So, now to start, I’ll be using the function print. Then I’ll write what I want the first part of what I want to write which is My favourite sports are: between the "". Then after I’ll add the seperator whcih is a comma and the function join to join them with the variable sports. And at the end, I’ll add another function called end= to end the senctence with a full stop and a new line so that we could write another command.
Here is what I wrote:
print("My favourite sports are:", ", ".join(sports), end='.\n')
And this is the output:
My favourite sports are: basketball, soccer, netball.
So this has been achieved but this is only the first part.
Display items in the list without join
Now here’s the second way to write the expected output. This way does not include the function join.
Reminder: It may not work on the python because the python is interactive so you should use a code writer for this
First, let’s show the simple bit which is My favourite sport is::
print("My favourite sport is:")
Now let’s do the hard bit. We want to print dino, robo, plush.. Let’s use the for loop (a function to loop) to do this. We also use the print function after to put a full stop at the end. However there would also be a comma too.
for i in sports:
print(i, end=', ') >>> print('.')
Now we’ve gotten that part. But could I do the expected output when I have one bit and another? So then this would be how we print the whole thing:
print("My favorite sports are:", end=" ")
# print everything except the last item in the list
for i in range(len(sports)-1):
print(sports[i], end=', ')
# print the last item, remove the space (' ') seperation, and add a '.'.
print(sports[-1], '.', sep='')
And what above I wrote will give the same expected output:
My favourite sports are: basketball, soccer, netball.
Thanks for reading!