How to print a Python list without brackets and commas
Sometimes when you are dabbling with Python lists, you might wish to print a list without the annoying brackets and commas that Python by default prints. For instance, consider the following code:
The output is:
Let us figure out how to get rid of the (square) brackets, commas, and even the quotes if you need so! There are at least four different ways to do so!
Method 1: Use the print function with a sep argument
The first approach is to use the print function, like above, but with a “sep” argument specifying the separator (in our case, we do not wish for any separator):
The output will be:
Method 2: Use a join method to concatenate after converting all parts to strings
In our second approach, we use the map function to convert all arguments to strings and then use the join function to concatenate them giving the empty string as the starting point for the join function:
The output is again:
Method 3: Use a traditional for loop and the end argument to avoid newlines
This approach is a bit traditional but illustrates how we can use a for loop with an end argument to achieve the same effect:
The output is:
Note that with this approach we do not print a newline at the end of all the printing: the cursor will be positioned just after the “r” in our string.
Method 4: Use the translate method
The translate method allows you to make modifications to a string, where some specified characters are replaced with the character described in a dictionary, or in a mapping table. For this purpose, we first create a dictionary and then use this dictionary in the translate() method:
Here the codes 32, 39, 44, 91, and 93 refer to the characters for space, starting and closing brackets, left square bracket, and right square bracket respectively. All these characters are mapped to ‘None’ in the dictionary which is then used in the translate method. The output is as before:
You have learnt four different ways to “sanitize” a list by removing brackets, commas, and spaces before printing it. Which one is your favorite?
Kodeclik is an online coding academy for kids and teens to learn real world programming. Kids are introduced to coding in a fun and exciting way and are challeged to higher levels with engaging, high quality content.