How to print variable number of elements using sep and end?

强颜欢笑 提交于 2019-12-12 04:54:58

问题


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

回答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)) )



回答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



回答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.



来源:https://stackoverflow.com/questions/29666797/how-to-print-variable-number-of-elements-using-sep-and-end

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!