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
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
>>> ','.join(map(str,a)) '1,2,3'
Method 2
A ','.join as suggested in other answers is the typical Python solution; the normal approach, which peculiarly I don’t see in any of the answers so far, is
print ','.join(str(x) for x in a)
known as a generator expression or genexp.
If you prefer a loop (or need one for other purposes, if you’re doing more than just printing on each item, for example), there are of course also excellent alternatives:
for i, x in enumerate(a): if i: print ',' + str(x), else: print str(x),
this is a first-time switch (works for any iterable a, whether a list or otherwise) so it places the comma before each item but the first. A last-time switch is slightly less elegant and it work only for iterables which have a len() (not for completely general ones):
for i, x in enumerate(a): if i == len(a) - 1: print str(x) else: print str(x) + ',',
this example also takes advantage of the last-time switch to terminate the line when it’s printing the very last item.
The enumerate built-in function is very often useful, and well worth keeping in mind!
Method 3
It’s very easy:
print(*a, sep=',')
Print lists in Python (4 Different Ways)
Method 4
There are two options ,
You can directly print the answer using
print(*a, sep=',')
this will use separator as “,” you will get the answer as ,
1,2,3
and another option is ,
print(','.join(str(x) for x in list(a)))
this will iterate the list and print the (a) and print the output as
1,2,3
Method 5
That’s what join is for.
','.join([str(elem) for elem in a])
Method 6
print ','.join(a)
Method 7
def stringTokenizer(sentense,delimiters):
list=[]
word=""
isInWord=False
for ch in sentense:
if ch in delimiters:
if isInWord: # start ow word
print(word)
list.append(word)
isInWord=False
else:
if not isInWord: # end of word
word=""
isInWord=True
word=word+ch
if isInWord: # end of word at end of sentence
print(word)
list.append(word)
isInWord=False
return list
print (stringTokenizer(u”привет парни! я вам стихами, может быть, еще отвечу”,”, !”))
Method 8
>>> a=[1,2,3] >>> a=[str(i) for i in a ] >>> s=a[0] >>> for i in a[1:-1]: s="%s,%s"%(s,i) ... >>> s=s+","+a[-1] >>> s '1,2,3'
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0