Matthew Yankey Matthew Yankey - 20 days ago 8
Python Question

Simplify nested loops and conditions in replacing string

I need assistance to simplify my code.
Code should check if there is only two letters to be replace then break the for loop:

word = "hesitation"
for i in word:
if i == 'a':
new_word = word.replace(i, '@')
for x in new_word:
if x == 'o':
new_word1 = new_word.replace(x, '0')
for n in new_word1:
if n == 's':
new_word2 = new_word1.replace(n, '$')
print new_word2

Answer

First of all instead of nested loops you can also do this in the following manner:

word = "hesitation"
for i in word:
    if i == 'a':
        word = word.replace(i, '@')
for x in word:
    if x == 'o':
        word = word.replace(x, '0')
for n in word:
    if n == 's':
        word = word.replace(n, '$')
print word

The above code is more efficient both time and space wise. Hope this helps.

Comments