Search code examples
pythonfunctionobjectreplaceattributeerror

AttributeError: 'function' object has no attribute 'replace'


I'm using this code to try to replace a character:

from another_test import test_once_more
test_once_more()
question = input("1 letter ")
for letter in question:
    if letter == "a":
        test_once_more.replace("1","a")
        print (test_once_more)

This is the code I am using. All I want it to do is replace the 1 in this code.

def test_once_more():
    print ("123456789")

and replace it with an "A"


Solution

  • You can't.

    The function is printing something and returns None. There's no way to change that after the fact.

    What you should do is have the function return a value and work on that:

    def test_once_more():
        return "123456789"
    

    and then

    from another_test import test_once_more
    result = test_once_more()
    question = input("1 letter ")
    for letter in question:
        if letter == "a":
            result = result.replace("1","a")
            print (result)
    

    although I'm puzzled why you're using a for loop to iterate over a string that will be a single character (at least if your user follows your request)...