Python函数在变量赋值期间打印输出

Python函数在变量赋值期间打印输出,python,Python,我希望下面的代码运行已定义的函数,并将已定义函数的输出保存在指定变量“functionsOutput”中。然后,我想用空格替换变量中的新行 但我下面的代码没有这样做。我做错了什么?将函数输出赋值给变量就是打印输出。我不想那样。我希望输出存储在变量中 #!/usr/bin/python2.7 mylist = [ "hello", "you", "are", "so", "cool" ] def printWithoutNewlines(): for objects in mylist:

我希望下面的代码运行已定义的函数,并将已定义函数的输出保存在指定变量“functionsOutput”中。然后,我想用空格替换变量中的新行

但我下面的代码没有这样做。我做错了什么?将函数输出赋值给变量就是打印输出。我不想那样。我希望输出存储在变量中

#!/usr/bin/python2.7
mylist = [ "hello", "you", "are", "so", "cool" ]

def printWithoutNewlines():
    for objects in mylist:
        objects = objects.replace('hello', "hi")
        print objects

functionsOutput = printWithoutNewlines()
functionsOutput.replace('\n', ' ')

下面的代码应该提供您想要的输出,但是您希望以这种方式完成它吗

mylist = [ "hello", "you", "are", "so", "cool" ]

def printWithoutNewlines():
    for objects in mylist:
        objects = objects.replace('hello', "hi")
        print objects,
    print

printWithoutNewlines()

您的函数正在打印结果,我认为您想要的是返回值。我可能是这样的:

objectsR = ""
for objects in mylist:
    objects = objects.replace('hello', "hi")
    objectsR = objectsR + objects
return objectsR

事实上,它有点复杂,因为需要添加空格等等。这样,您就不需要替换了。

这里出现了几个错误:

  • 您的函数不返回任何内容。在挥手告别之前,它做的最后一件事就是打印
  • 您正在为迭代器分配一个新值。这使得 循环中的语句已过时
  • 如果您纠正了这些错误,您甚至不必删除
    \n
    字符

    #!/usr/bin/python2.7
    mylist = [ "hello", "you", "are", "so", "cool" ]
    
    def printWithoutNewlines():
        output = ""
        for objects in mylist:
            output += objects.replace('hello', "hi")
        return output
    
    functionsOutput = printWithoutNewlines()
    print functionsOutput
    >>> hiyouaresocool
    

    返回的
    在哪里?您应该从函数返回以获取
    functionsOutput
    中的值。分配不会打印。这是print命令的作用(很明显)。我把你的问题作为我的问题的一个副本关闭的问题乍一看似乎不是你问题的解决方案,但它确实是。基本问题是您误解了变量在Python中的工作方式。我链接的问题有一些很好的答案,解释了Python变量的细微差别。除了我上面提到的问题外,另一本好书是Ned Batchelder的。请提供上下文和缩进。