-2

I can't sep="_" in my code

How can i do.

'''python'''
def sequence(num):
    for i in range(1, num+1):
        print(i, sep="_", end=""
sequence()
num = 6
i want = 1_2_3_4_5_6
but it show = 123456
Pl_P
  • 51
  • 1
  • 6

1 Answers1

1

The sep argument in the print function is used only when you pass several objects first.

For example:

print(1, 2, 3, 4, 5, 6, sep="_")

would print:

>> 1_2_3_4_5_6

As Thierry explains, the end parameter would be the one repeated at each iteration in the given code, but that would result in an extra _ at the end of the string, which is not what's requested.

One way to achieve the requested result would be something like:

def sequence(num):
    print(*[x for x in range(1, num+1)], sep='_')

Notice the use of * in front of the list of numbers, so that they get expanded. In this case, sep argument works as expected.

sal
  • 3,515
  • 1
  • 10
  • 21