I have got a string alphabet = "abcdefghijklmn" and would like to replace each vowel in the string with values from a substitution matrix matrix = { 'a' : 'FIRST VOWEL', 'e' : 'SECOND VOWEL', 'i' : 'THIRD VOWEL' }. I guess this is a case for recursion, so I tried the following function:
import re
def iterrepl(string):
m = re.search(r'[aeiou]',string)
if m:
string = string[:m.start()]+matrix.get(m.group())+string[m.end():]
iterrepl(string)
else:
return(string)
matrix = { 'a' : 'FIRST VOWEL', 'e' : 'SECOND VOWEL', 'i' : 'THIRD VOWEL' }
alphabet = "abcdefghijklmn"
print(iterrepl(alphabet))
The final result, however, is None, whereas I was hoping for FIRST VOWELbcdSECOND VOWELfghTHIRD VOWELjklmn. When I add a print statement before calling iterrepl within the function, I can see that the result of the last but one recursion is the desired one:
FIRST VOWELbcdefghijklmn
FIRST VOWELbcdSECOND VOWELfghijklmn
FIRST VOWELbcdSECOND VOWELfghTHIRD VOWELjklmn
None
I cannot figure out what is wrong with the end of the recursion and would appreciate any advice!
return iterrepl(string)otherwise what's it returning?str.translatedo the work for you.trans=str.maketrans({ 'a' : 'FIRST VOWEL', 'e' : 'SECOND VOWEL', 'i' : 'THIRD VOWEL' });print("abcdefghijklmn".translate(trans))