Printing from a for loop with separators between each element but not at the end

Question:

How can I make sure that there is nothing at the end of the last print statement instead of "-"?

for i in range(0, 4,):
    print(i, end="-")
print()
for i in range(0, 10, 2):
    print(i, end="-")
Asked By: bludum8

||

Answers:

As deadshot mentioned above, you should use sep.

Instead of

for i in range(0, 4,):
    print(i, end="-")
print()
for i in range(0, 10, 2):
    print(i, end="-"

Try:

print( *range(0, 4), sep='-' )
print( *range(0, 10, 2), sep='-')
Answered By: AdmiJW

You can use the join method of strings to get your desired output (you need to transform the numbers to strings):

print("-".join(str(i) for i in range(0, 4)))
print("-".join(str(i) for i in range(0, 10, 2)))

Alternatively you can use the sep argument of the print function and unpack the range:

print(*range(0, 4), sep="-")
print(*range(0, 10, 2), sep="-")

Unpacking range(x, y) will have the same result as if you were passing multiple arguments to print. When you do so, the print function will join those inputs, by default it would join with a space but with the sep argument you can override the string used for joining

Answered By: Matteo Zanoni
for i in range(0, 4,):
    print(i, sep="-")
print()
for i in range(0, 10, 2):
    print(i, sep="-")
Answered By: Vivs
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.