Skip to content Skip to sidebar Skip to footer

How To Print Variable Number Of Elements Using Sep And End?

I've been trying to use the sep='' to separate the numbers in between each other but they never separate unless I use end=''. However, when I switch sep='' with end='' it works pro

Solution 1:

You can use string join function to join item in the list with some string, here is example

a = [1,2,3,4]
'+'.join( map(str,a))
<<< '1+2+3+4'

so your case should be

print( ' '.join(map(str,numbers)) )

Solution 2:

If you look at the documentation for the print-function. It takes a variable numbers to print out separated by the given sep and ended with end. So you can simply use the *syntax to pass your sequence to print. Simply:

>>>print(*range(1,5))
1 2 3 4
>>>print(*range(1,5), sep='+')
1+2+3+4
>>>print(*range(1,5), sep='+', end='=' + str(sum(range(1,5))))
1+2+3+4=10

Solution 3:

You're using numbers in a for loop. Even though the variable name is plural, it only gets one value at a time. i.e., if s_num==1 and e_num==2, the for loop will be unfolded to the following:

numbers=1
print(1, sep='')
numbers=2
print(2, sep='')

As you see, numbers takes a single value from the range each time through the for loop, not the whole range. sep is used to separate multiple values being printed out from a variable list of arguments passed to the print function. Since there is only a single value being printed out in each print statement, there is nothing to separate so setting sep does nothing.

Post a Comment for "How To Print Variable Number Of Elements Using Sep And End?"