我刚刚写了一个代码,它得到一个起始编号,结束编号和一个步骤(它是一个范围)并打印所有数字。 它工作得很好,但我希望输出也是一个字符串。
这是我的代码:
def count(num1,num2,steps):
getfirstnum=int(raw_input(num1))
getsecondenum=int(raw_input(num2))
getsteps=int(raw_input(steps))
for num in range(getfirstnum,getsecondenum,getsteps):
print 'in bettwen: ',num
return num
def Main():
Getnum=count('Give me the 1st number: ','Give me the 2nd number: ','How many Steps?: ')
if __name__ == "__main__":
Main()
现在如果我要插入: 第一个数字:1 第二个数字:10 步骤:2
我会得到结果:
in bettwen: 1
in bettwen: 3
in bettwen: 5
in bettwen: 7
in bettwen: 9
如何将输出变为字符串? 感谢。
答案 0 :(得分:1)
试试这个:
def whatever(start, stop):
result = ''
for num in range(start,stop):
result += str(num)
return result
print(whatever(0,5))
01234
答案 1 :(得分:0)
def count(num1,num2,steps):
string_output = ""
getfirstnum=int(raw_input(num1))
getsecondenum=int(raw_input(num2))
getsteps=int(raw_input(steps))
for num in range(getfirstnum,getsecondenum,getsteps):
string_output += str(num)
return string_output
答案 2 :(得分:0)
...
print 'in bettwen: ' + str(num)
...
或者,如果您正在寻找不同的东西:
string = 'in bettwen: '
for num in range(getfirstnum,getsecondenum,getsteps):
string += " " + str(num)
return num
答案 3 :(得分:0)
使用join
和生成器:
>>> ''.join(str(n) for n in range(1,10,2))
'13579'
这相当于:
>>> s = ''
>>> for n in range(1,10,2):
... s += str(n)
...
>>> s
'13579'