Here's how to modify existing code so that it does what you want. I changed newWord
to new_word
according to the standard Python style convention.
def replace(char, word1, word2): new_word = "" for i in range(len(word2)): if word1[i] == char: new_word += char else: new_word += word2[i] return new_word # Test print(replace("p", "apple", "12345"))
Output
1pp45
Note that this code will raise an IndexError: string index out of range
exception IndexError: string index out of range
if word1
shorter than word2
.
There are various ways to implement this function. First, we can use the zip
function to iterate the characters of both lines in parallel. This is a little cleaner than your indirect iteration, using string indices to access characters.
def replace(char, word1, word2): new_word = "" for c1, c2 in zip(word1, word2): if c1 == char: new_word += char else: new_word += c2 return new_word
Note that if the lines are the same length, then the zip
stop gracefully when the shorter line ends.
We can make this code more compact by replacing the if... else
block with a conditional expression.
def replace(char, word1, word2): new_word = "" for c1, c2 in zip(word1, word2): new_word += char if c1 == char else c2 return new_word
A more advanced version uses list comprehension to create a list of desired characters and a .join
string .join
to convert that list to a string.
def replace(char, word1, word2): return ''.join([char if c1 == char else c2 for c1, c2 in zip(word1, word2)])
This can also be done using a generator expression.
''.join(char if c1 == char else c2 for c1, c2 in zip(word1, word2))
However, this is less effective than using list comprehension because .join
works. .join
should double-check its argument: the first scan is used to calculate the total size of the output string, the second scan is the actual connection. But you cannot scan the generator twice, so if you pass .join
generator, it must create a temporary list from the generator.