Question :
I have a list in Python
e.g.
names = ["Sam", "Peter", "James", "Julian", "Ann"]
I want to print the array in a single line without the normal ” []
names = ["Sam", "Peter", "James", "Julian", "Ann"]
print (names)
Will give the output as;
["Sam", "Peter", "James", "Julian", "Ann"]
That is not the format I want instead I want it to be like this;
Sam, Peter, James, Julian, Ann
Note: It must be in a single row.
Answer #1:
print(', '.join(names))
This, like it sounds, just takes all the elements of the list and joins them with ', '
.
Answer #2:
Here is a simple one.
names = ["Sam", "Peter", "James", "Julian", "Ann"]
print(*names, sep=", ")
the star unpacks the list and return every element in the list.
Answer #3:
General solution, works on arrays of non-strings:
>>> print str(names)[1:-1]
'Sam', 'Peter', 'James', 'Julian', 'Ann'
Answer #4:
If the input array is Integer type then you need to first convert array into string type array and then use join
method for joining with ,
or space whatever you want. e.g:
>>> arr = [1, 2, 4, 3]
>>> print(", " . join(arr))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: sequence item 0: expected string, int found
>>> sarr = [str(a) for a in arr]
>>> print(", " . join(sarr))
1, 2, 4, 3
>>>
Direct using of join which will join the integer and string will throw error as show above.
Answer #5:
There are two answers , First is use ‘sep’ setting
>>> print(*names, sep = ', ')
The other is below
>>> print(', '.join(names))
Answer #6:
This is what you need
", ".join(names)
Answer #7:
','.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]
Answer #8:
You need to loop through the list and use end=" "
to keep it on one line
names = ["Sam", "Peter", "James", "Julian", "Ann"]
index=0
for name in names:
print(names[index], end=", ")
index += 1