如何使用sep打印可变数量的元素并结束? [英] How to print variable number of elements using sep and end?
问题描述
我一直试图用 sep =''
来区分彼此之间的数字,但是除非我用 end =
。
然而,当我用 end =
切换 sep =''
时,它可以正常工作。
那么,我做错了什么?
另外,如何在+
符号之间分隔数字,而不会出现在最后?
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
推荐答案
如果您查看 print
- 功能。它需要一个可变数字来打印输出,由给定的 sep
分隔,并以 end
结尾。因此,您可以简单地使用 *语法
将序列传递给 print
。简单地说:
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
这篇关于如何使用sep打印可变数量的元素并结束?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!