I have a list in Python e.g.
names = [\"Sam\", \"Peter\", \"James\", \"Julian\", \"Ann\"]
I want to print the array in a single line withou
I don't know if this is efficient as others but simple logic always works:
import sys
name = ["Sam", "Peter", "James", "Julian", "Ann"]
for i in range(0, len(names)):
sys.stdout.write(names[i])
if i != len(names)-1:
sys.stdout.write(", ")
Output:
Sam, Peter, James, Julian, Ann
print(', '.join(names))
This, like it sounds, just takes all the elements of the list and joins them with ', '
.
print(*names)
this will work in python 3 if you want them to be printed out as space separated. If you need comma or anything else in between go ahead with .join() solution
This is what you need
", ".join(names)
General solution, works on arrays of non-strings:
>>> print str(names)[1:-1]
'Sam', 'Peter', 'James', 'Julian', 'Ann'
','.join(list)
will work only if all the items in the list are strings. If you are looking to convert a list of numbers to a comma separated string. such as a = [1, 2, 3, 4]
into '1,2,3,4'
then you can either
str(a)[1:-1] # '1, 2, 3, 4'
or
str(a).lstrip('[').rstrip(']') # '1, 2, 3, 4'
although this won't remove any nested list.
To convert it back to a list
a = '1,2,3,4'
import ast
ast.literal_eval('['+a+']')
#[1, 2, 3, 4]