I am Trying to make a program in Python to reverse the vowels in a string and return the string like this:
vow = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']
vowin = []
place = []
def string(string):
for ch in string:
if ch in vow:
vowin.append(ch)
else:
continue
for ch in string:
if ch in vow:
index1 = string.index(ch)
place.append(index1)
else:
continue
place.reverse()
str = list(string)
for ch in range(len(place)):
str[place[ch]] = vowin[ch]
new = ''.join(str)
return new
print(string('Queen'))
When I try to run a word with a double vowel like queen it makes all other vowels into e too like the code above.
Output: Qeeen
but if I input hello the output is holle like it should.
Anyone know what the problem is?
CodePudding user response:
No indexing required if vowin
is used as a LIFO (last in, first out) stack. First pass, fill with vowels in order. Second pass, each vowel is replaced from vowin
via .pop()
which removes the last value.
vow = 'aeiouAEIOU'
def string(s):
vowin = [] # make sure to reset each call to string()
place = []
for ch in s:
if ch in vow:
vowin.append(ch) # store vowels in order found
for ch in s:
if ch in vow: # if vowel
place.append(vowin.pop()) # replace in reverse order
else:
place.append(ch) # else copy as is
new = ''.join(place)
return new
print(string('Queen'))
print(string('abcdefghijklmnopqrstuvwxyz'))
print(string('bookkeeping'))
Output:
Qeeun
ubcdofghijklmnepqrstavwxyz
biekkeopong
CodePudding user response:
Change this part:
for ch in string:
if ch in vow:
index1 = string.index(ch)
place.append(index1)
else:
continue
to
for i, ch in enumerate(string):
if ch in vow:
place.append(i)
CodePudding user response:
this code uses a list comprehension to extract the vowels from the input string. the resampling of the final string is done by using a ternary conditional.
inp = input()
vow = 'aeiouAEIOU'
vow_lst = [char for char in inp if char in vow]
res = ''
for char in inp:
res = vow_lst.pop() if char in vow else char
print(res)