-2

I want the following code to run the defined function, and save the output of the defined function in the specified variable "functionsOutput". And then, I want to replace the new lines in the variable with spaces.

But my code below isn't doing that. What am i doing wrong? The assignment of the function output to a variable is printing out the output. I don't want that. I want the output stored in the variable.

#!/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', ' ')
swenson
  • 67
  • 6
  • 1
    Where is `return`? You should return from function to get value in `functionsOutput`. – Austin May 28 '18 at 14:57
  • 1
    The assignment doesn't print. It's the print-command which does that (obviously). – offeltoffel May 28 '18 at 14:59
  • The question I closed your question as a duplicate of my not seem like a solution to your problem at first blush, but it does. Your fundamental problem is that you misunderstand how variables work in Python. The question I linked to have some good answers explaining the nuances of Python variables. In addition to the question I linked to above, another good read is Ned Batchelder's [_Facts and myths about Python names and values_](https://nedbatchelder.com/text/names.html). – Christian Dean May 28 '18 at 15:13

3 Answers3

0

The following code should give the output you desire, but do you want to accomplish it in that way?

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

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

printWithoutNewlines()
Sam Chats
  • 2,271
  • 1
  • 12
  • 34
0

Several mistakes come together here:

  1. Your function does not return anything. The last thing it does before waving goodbye is printing.
  2. You are assigning a new value to the iterator. That makes the statement within your loop obsolete.

If you correct these mistakes, you won't even have to delete the \n character.

#!/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
offeltoffel
  • 2,691
  • 2
  • 21
  • 35
-2

Your function is printing the result and I think what you want is to return the values. I could be something like:

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

In fact, it is a bit more complicated because you'll need to add spaces and so on. Then, you won't need the substitution.

fernand0
  • 310
  • 1
  • 10