Python - comma separated list of prints

I am writing a piece of code that should list comma separated items. The list is created using the for loop. I use

for x in range(5):
    print(x, end=",")

The problem is that I do not know how to get rid of the last comma that is added with the last entry in the list. He outputs this:

0,1,2,3,4,

How to remove the ending ','?

+5
source share
4 answers

Pass sep=","as an argumentprint()

You are almost there with an expression for print.

There is no need for a loop, print has a parameter sepas well end.

>>> print(*range(5), sep=", ")
0, 1, 2, 3, 4

Little explanation

print . , sep. sep .

>>> print("hello", "world")
hello world

sep .

>>> print("hello", "world", sep=" cruel ")
hello cruel world

, str(). print , .

>>> print(["hello", "world"], sep=" cruel ")
['hello', 'world']

, , sep.

>>> print(*["hello", "world"], sep=" cruel ")
hello cruel world

>>> print(*range(5), sep="---")
0---1---2---3---4

join

join .

>>>print(" cruel ".join(["hello", "world"]))
hello cruel world

, .

>>>print(",".join([str(i) for i in range(5)]))
0,1,2,3,4

-

, , , , . , , .

>>>iterable = range(5)
>>>result = ""
>>>for item, i in enumerate(iterable):
>>>    result = result + str(item)
>>>    if i > len(iterable) - 1:
>>>        result = result + ","
>>>print(result)
0,1,2,3,4
+11

str.join() , , . -

print(','.join([str(x) for x in range(5)]))

-

>>> print(','.join([str(x) for x in range(5)]))
0,1,2,3,4

, , , str.join.

+3

str.join().

In [1]: print ','.join(map(str,range(5)))
0,1,2,3,4

range(5), str.join(). map(). , map(), ,.

+2

Another form you can use is closer to the source code:

mysep="" # no separator on first print
for x in range(5):
    print (mysep,x,sep="") # don't let print use default separator
    mysep="," # use comma for prints after the first one

Of course, the goal of your program is probably better served by other, more pythonic answers in this thread. However, in some situations this may be a useful method.

0
source

Source: https://habr.com/ru/post/1609088/


All Articles