【发布时间】:2015-04-21 17:28:52
【问题描述】:
def digits_plus(test):
test=0
while (test<=3):
print str(test)+"+",
test = test+1
return()
digits_plus(3)
输出是: 0+ 1+ 2+ 3+
但是我想得到:0+1+2+3+
【问题讨论】:
def digits_plus(test):
test=0
while (test<=3):
print str(test)+"+",
test = test+1
return()
digits_plus(3)
输出是: 0+ 1+ 2+ 3+
但是我想得到:0+1+2+3+
【问题讨论】:
另一种方法是创建一个数字列表,然后加入它们。
mylist = []
for num in range (1, 4):
mylist.append(str(num))
我们得到列表 [1, 2, 3]
print '+'.join(mylist) + '+'
【讨论】:
如果您在使用 Python 2.7 时遇到问题,请使用以下命令启动您的模块
from __future__ import print_function
然后代替
print str(test)+"+",
使用
print(str(test)+"+", end='')
您可能需要在末尾添加 print()(在循环之外!-),以便在打印完其余部分后换行。
【讨论】:
您还可以使用sys.stdout 对象将输出(到标准输出)写入您可以更好地控制的输出。这应该可以让你准确地输出你告诉它的字符(而 print 会为你做一些自动换行和强制转换)
#!/usr/bin/env python
import sys
test = '0'
sys.stdout.write(str(test)+"+")
# Or my preferred string formatting method:
# (The '%s' implies a cast to string)
sys.stdout.write("%s+" % test)
# You probably don't need to explicitly do this,
# If you get unexpected (missing) output, you can
# explicitly send the output like
sys.stdout.flush()
【讨论】: