我正在嘗試用 Python 撰寫一個程式來反轉字串中的元音并回傳如下字串:
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'))
當我嘗試用雙元音(如女王)運行一個單詞時,它會使所有其他元音變成 e 也像上面的代碼一樣。
輸出:Qeeen
但是如果我輸入 hello 輸出是 holle 應該的。
有誰知道問題是什么?
uj5u.com熱心網友回復:
vowin如果用作 LIFO(后進先出)堆疊,則不需要索引。第一遍,按順序填充元音。第二遍,每個元音都被替換,vowin通過.pop()洗掉最后一個值。
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'))
輸出:
Qeeun
ubcdofghijklmnepqrstavwxyz
biekkeopong
uj5u.com熱心網友回復:
更改此部分:
for ch in string:
if ch in vow:
index1 = string.index(ch)
place.append(index1)
else:
continue
至
for i, ch in enumerate(string):
if ch in vow:
place.append(i)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/527614.html
標籤:Python细绳列表
上一篇:包圍所有字符
下一篇:嵌套字典的任意長度的元組串列
