0

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="-")
Henry Ecker
  • 34,399
  • 18
  • 41
  • 57
bludum8
  • 3
  • 1

3 Answers3

3

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

Matteo Zanoni
  • 3,429
  • 9
  • 27
0

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='-')
AdmiJW
  • 83
  • 6
  • 1
    That will surely work, but it would be better to give the author an explanation of what you are doing, since they are just starting with Python programming. – accdias Nov 14 '22 at 14:40
-1
for i in range(0, 4,):
    print(i, sep="-")
print()
for i in range(0, 10, 2):
    print(i, sep="-")
Vivs
  • 447
  • 4
  • 11
  • 1
    This is exactly his code... Please provide an answer – Matteo Zanoni Nov 14 '22 at 14:44
  • read properly "end" needs to be changed with "sep" @MatteoZanoni – Vivs Nov 14 '22 at 14:49
  • 2
    Including a bit of explanation in your answer can help make it clearer for people reading your answer what changes have been made so that they can learn and apply your solution to their use-case. – Henry Ecker Nov 15 '22 at 02:04
  • Also this will print each number on a separate line and the `sep` keyword is useless since you are only passing one argument to `print`. – Matteo Zanoni Nov 15 '22 at 10:40