0

我一直在阅读在打印命令末尾添加逗号会水平而不是垂直列出函数的所有输出字符串。但不知何故,我的格式不允许我这样做

def foo(Y):
...
...
print foo(Y),

这仍然给了我

a
b
c

代替

a b c

编辑:我的特定功能是迭代的,在另一个功能上

def encode(Y):
    for i in range(0, len(Y), 2):
        encode_pair(Y[i], Y[i+1]),
4

3 回答 3

3

这可能是因为您正在处理字符串,并且\n在它的末尾或开头有一个字符。可以肯定的是,没有开头或结尾的空格,请使用strip(). 所以:

print str(foo(Y)).strip()

这是在您的函数返回某些内容的假设下,否则,上面的示例将不起作用。如果 Y 是全局的,并且您的函数实际上更改了一个全局变量:

for var in Y:
    print var,
于 2013-10-31T14:58:19.820 回答
0

您的功能似乎只打印。所以你应该修改它。如果你不能这样做,你将不得不stdout暂时重定向:

import cStringIO
import sys
buf = cStringIO.StringIO()

sys.stdout = buf
*do your printing calls*
sys.stdout = sys.__stdout__

output = buf.getvalue()
# This is now a string with all the output.

print output.replace('\n', ' ') # Output it with line breaks replaced with spaces.

如果你经常做这样的事情,你可以做

import contextlib
@contextlib.contextmanager
def redir_stdout(temptarget):
    import sys
    try:
        t = sys.stdout
        sys.stdout = temptarget
        yield None
    finally:
        sys.stdout = t

接着

import cStringIO
buf = cStringIO.StringIO()

with redir_stdout(buf):
    *do your printing calls*

output = buf.getvalue()
# This is now a string with all the output.    
于 2013-10-31T15:25:22.837 回答
0

foo函数必须返回一个末尾带有换行符的字符串。尝试:

print foo(Y).rstrip(),

如果您尝试此操作并且在仍然看到 output 时NoneType遇到错误,则打印必须在您的函数内部进行,而不是在此语句中进行。逗号只能影响该特定语句,而不是函数内部的一个。在函数内部搜索并删除或将逗号放在内部语句上。或者您想要打印并在外部打印的值。printprintreturn

于 2013-10-31T14:54:43.970 回答