user3595866
user3595866

Reputation: 129

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"

Upvotes: 3

Views: 22831

Answers (2)

Tim Pietzcker
Tim Pietzcker

Reputation: 336378

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)...

Upvotes: 4

Michael Aaron Safyan
Michael Aaron Safyan

Reputation: 95569

You have a very simple error here; test_once_more is the name of your function, while question is the name of your string. Try question.replace (and fix the other similar mistake).

P.S. strings cannot be mutated in Python, so you need to assign the result of calling replace to another variable in order to see the effect of calling replace().

Upvotes: 0

Related Questions