There's a number of issues here; let's break them down without altering your original code too much:
You function definition lacks a name, define it with a name properly. For example:
def replace_a(string_a, substring): ...
I'm guessing this might be a copy-paste omission.
if letter ! = "a": is a SyntaxError, ! = doesn't get interpreted as != (but as two separate operators ! and =), unfortunately, that needs fixing too.
elif letter = "a": is another SyntaxError; assignment statements should not be confused with equality checks, that is = is not similar to using ==.
new_string.append(letter) is a TypeError; the method append isn't defined for strings, strings are immutable and appending is a method that mutates the object. append is available on lists.
a = substring isn't doing much :-(. You assign to a and then simply don't use it.
- FInally, you don't return anything. Even if your function created the string correctly, you can't get it back because your don't use the
return statement.
One approach you could consider is to use a list of character strings and mutate that; lists are mutable so mutate to your hearts desire. Then, you join the list in the end and return a string out of all the characters inside it:
def replace_a(string1, substring):
new_string= []
for letter in string1:
if letter != "a":
new_string.append(letter)
elif letter == "a":
new_string.append(substring)
return "".join(new_string)
This yields your wanted result.
If you can't use a list, mutate it and then join you could resort to incrementally building a new string:
def replace(string1, substring):
new_string= ""
for letter in string1:
if letter != "a":
new_string += letter
elif letter == "a":
new_string += substring
return new_string
This again behaves like the previous list based function but relies on += which creates new strings by joining the old value in new_string with the letter or the substring based on the condition.
Of course, .replace on strings would do the trick as the comment by @yper suggests but that beats the point of explaining how your attempt didn't achieve what you were after.
You were close but missing a couple of basic things, I'd advice you take a look at the Python Tutorial. :-)
string1.replace("a", substring)?