0

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 properly. So, what am I doing wrong? Also, how do I separate the numbers in between with a "+" symbol without having it appear at the end?

Thanks!

#Counter
numcounter=0
#Get starting integer from user

s_num=int(input("Please enter a valid starting integer number: "))

#Get ending integer from user

e_num=int(input("Please enter a valid ending integer number: "))

#For loop

for numbers in range (s_num,e_num+1):
    numcounter+=numbers
    print(numbers, sep='')

This was the output:

Python 3.4.1 (v3.4.1:c0e311e010fc, May 18 2014, 10:38:22) [MSC v.1600 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> ================================ RESTART ================================
>>> 
Please enter a valid starting integer number: 1
Please enter a valid ending integer number: 5
1
2
3
4
5
RickardSjogren
  • 4,070
  • 3
  • 17
  • 26
natokwa
  • 1
  • 4

3 Answers3

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)) )
Chetchaiyan
  • 261
  • 2
  • 11
  • I technically haven't "learned" that yet so I can't use it. I know it can be done just by use sep= and end= but I don't know how to use them properly. – natokwa Apr 16 '15 at 06:32
  • Doesn't work any way, gives `TypeError: sequence item 0: expected str instance, int found`. You need to convert the numbers to strings first, like `print( ' '.join(map(str, numbers) ) )` – RickardSjogren Apr 16 '15 at 06:33
  • Sorry, just missing to convert integer to string – Chetchaiyan Apr 16 '15 at 06:45
1

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
RickardSjogren
  • 4,070
  • 3
  • 17
  • 26
-1

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.

space
  • 377
  • 2
  • 6