+ 1
how can I write a code that replaces each consonant in a file with a vowel? I tried a code that only works for the last consonant. I don't know why and I am getting tired of trying alone
A coding nightmare!!!
9 odpowiedzi
0
this is the code:
text = "this is fun"
vowel= ["a","e","i","o","u"]
def translate(file):
for i in file:
if i in file and i not in vowel:
a= file.replace (i,"o")
return a
print(translate(text))
please help me find the reason why it only works for the last consonant.
0
your code doesnt work.
Try this:
text = "this is fun"
vowel= ["a","e","i","o","u"]
def translate(file):
a = ""
for i in file:
if i not in vowel:
a+="o"
else:
a+=i
return a
print(translate(text))
0
Pavel thanks. a="" is a string that changes value for each non vowel element that of the file parameter. but I don't understand how the interpreter knows that a replaces the consonants. can you pls explain that part of the code?
0
okay, lets see how code work step by step.
At firts we created string variable with name @a@ and its value is empty string.
a = ""
Next, we create a loop, which iterate over @file@ function parameter. In our case that mean that body loop will execute 11 times (because len(file) in our case = len("this is fun") and in every iteration @i@ will take corresponding value:
0 - t
1- h
2 - i
3 - s ....etc
for i in file:
in every iteration we check that the current letter of our text (@i@) doesnt contains in @vowel@ list. If its true, we append to our answer string @a@ letter "o", in other case we append @i@ value.
if i not in vowel:
a+="o"
else:
a+=i
Remember, this works in every iteration of the loop!
i = 't' True a="o"
i='h' True a="oo"
i='i' False a="ooi"
i='s' True. a="ooio"
........
And after all iterations we return @a@ value from our function:
return a
0
wow!!! Pavel. you explained it very well. now I understand it. thanks i appreciate it.
0
You are welcome:)
0
hi
0
remember across for attention down for affection
- 1
hi wa dz. I've been trying to prime myself by solving some Python problems online. building algorithms like; bubble, merge, quick sort etc. it has been all about cramming without really understanding my code. so I went back to smaller problems.