Reputation: 135
I have a question on my coding. I'm writing a code that with every OTHER instance of the letter "a" in a string, it needs to be replaced by "dragon". So if the string was abadifaa, my code should return "abdragondifadragon."
So far, I have written the code for replacing every instance of "a"
def replace(string1, dragon):
new_string = " "
for letter in string1:
if letter != "a":
new_string +=letter
elif letter == "a':
new_string += dragon
return new_string
So I have 2 questions. 1. Is my code correct if the question asked for every instance of "a" to be replaced? 2. How would I change this code to iterate and replace through only every other instance of "a"?
Appreciate the help!
Upvotes: 0
Views: 104
Reputation: 1639
First of all, you need to indent your function definition:
def replace(string1, dragon):
new_string = " "
for letter in string1:
if letter != "a":
new_string +=letter
elif letter == "a':
new_string += dragon
return new_string
Also, it's more readable not to double-space lines.
Secondly, dragon
is a variable, not a string. Here I default dragon to the string 'dragon':
def replace(string1, dragon='dragon'):
new_string = " "
for letter in string1:
if letter != "a":
new_string +=letter
elif letter == "a':
new_string += dragon
return new_string
However it is better to rename the variable:
def replace(string1, replace_word='dragon'):
new_string = " "
for letter in string1:
if letter != "a":
new_string +=letter
elif letter == "a':
new_string += replace_word
return new_string
Now, you want to replace every other 'a'. Easy way, and intuitive (there are many other clever ways, but for beginners, this is easiest to understand). Create a counter of a's, and only replace if the modulo when divided by 2 is zero. This means every even number of a_counter
, which is every other instance of a.
def replace(string1, replace_word='dragon'):
a_counter = 0
new_string = ''
for letter in string1:
if letter != 'a':
new_string += letter
elif letter == 'a':
a_counter += 1
if a_counter%2 == 0:
new_string += replace_word
else:
new_string += letter
return new_string
print replace('abadifaa', 'dragon')
Also, your quotes are not correct (fixed above, you were mixing '
and ""
), and your return is nested too deep (you want to only return once you have iterated over all the letters).
Here is a coderpad to see it in action: https://coderpad.io/KPM3K7PG
(edited a few mistakes from original answer, like appending all letters).
Upvotes: 1
Reputation: 76
You have forgotten a few quotation marks and your new_string
should be empty (you have a space in it now). Other than these, your code changes every instance of "a" to "dragon". I would recommend adding a counter variable into your code, so that every time the counter is an even number, the letter "a" is replaced and every time it is an odd number, it is left as-is.
Upvotes: 0