Consider this Python code for printing a list of comma separated values
for element in list: print element + ",",
What is the preferred method for printing such that a comma does not appear if element
is the final element in the list.
ex
a = [1, 2, 3] for element in a print str(element) +",", output 1,2,3, desired 1,2,3
If you just want to know the best way to print a list in Python, here's the short answer: Pass a list as an input to the print() function in Python. Use the asterisk operator * in front of the list to “unpack” the list into the print function. Use the sep argument to define how to separate two list elements visually.
When you wish to print the list elements in a single line with the spaces in between, you can make use of the "*" operator for the same. Using this operator, you can print all the elements of the list in a new separate line with spaces in between every element using sep attribute such as sep=”/n” or sep=”,”.
use join() function to print array or without square brackets or commas.
How to Convert a Python List into a Comma-Separated String? You can use the . join string method to convert a list into a string. So again, the syntax is [seperator].
>>> ','.join(map(str,a)) '1,2,3'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With