我目前正在開發一個小而有趣的程式,該程式將名稱作為輸入并在名稱中的每個元音后回傳帶有字串“bi”的名稱。
我遇到的問題是,當我的名字兩次具有相同的相同元音時,我的程式會無限回圈運行,例如:名字“aya”。從技術上講,它應該回傳“abiyabi”
"""Welcome to the code of BoBi Sprache. This Sprache aka Language will
put the letter "bi" after each vowel letter in your name"""
print("Welcome to the BoBiSprache programm")
Name = input("Please enter your name to be BoBied :D : ")
NameList = list(Name.lower())
vowels = ["a", "e", "i", "o", "u"]
def VowelCheck(NameList):
for i in NameList:
index = NameList.index(i)
for j in vowels:
if i == j and index == 0:
NameList.insert(index 1, "bi")
elif i == j and (str(NameList[index - 1]) str(NameList[index])) != "bi":
NameList.insert(index 1, "bi")
VowelCheck(NameList)
NewName = ""
NewName = (NewName.join(NameList)).title()
print("Your New Name is: %s" % NewName)
我首先認為這是第一個字母是元音的問題。但我添加了一個 if 陳述句來解決這個問題。老實說,我現在沒有答案,正在尋求幫助。你們可能會看到一些我看不到的東西。
uj5u.com熱心網友回復:
獨立于用戶提交的名稱構建 Bobied 名稱。另請注意,字串在 Python 中是可迭代的,無需將用戶提交的名稱轉換為串列。
username = input("Please enter your name to be BoBied :D : ")
vowels = ["a", "e", "i", "o", "u"]
def VowelCheck(name):
bobified_name = ""
for i in name:
bobified_name = i
if i in vowels:
bobified_name = "bi"
return bobified_name
print("Your New Name is: %s" % VowelCheck(username).title())
現在,如果你想避免回圈和條件,或者有大量的輸入:使用str.translate(). 首先制作一個翻譯表,dict將元音映射到元音化元音。然后呼喚translate()名字被bobified。
username = input("Please enter your name to be Bobied :D : ")
bobi_table = str.maketrans({
'a': 'abi',
'e': 'ebi',
'i': 'ibi',
'o': 'obi',
'u': 'ubi'
})
print("Your new name is: %s" % username.translate(bobi_table))
uj5u.com熱心網友回復:
您的函式不斷回圈的原因是,正如您所說,您有兩次相同的元音,同時您還搜索了元音的索引。問題是該index方法回傳正在搜索的值的第一個實體。當您迭代到串列的下一個元素時,它保持與之前相同的值,因為您在迭代串列時正在編輯串列。它也不會是“bi”,因為它是在元音的第一個實體之后添加的。
不建議在迭代期間編輯串列。最佳做法是創建一個新串列并向其附加值。
uj5u.com熱心網友回復:
您也可以通過使用str.translatewhich 您可以提供多個字符來將一個字符更改為多個來做到這一點:
username = input("Please enter your name to be BoBied :D : ")
vowels = ["a", "e", "i", "o", "u"]
vowels = [i.upper() for i in vowels]
translation_table = str.maketrans({i: i "bi" for i in vowels})
print((f"Your BoBied name is: {username.translate(translation_table)}"))
演示:
Please enter your name to be BoBied :D : Hampus
Your BoBied name is: Habimpubis
我還添加了大寫字母,這樣用戶在什么情況下輸入他們的名字都沒有關系。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/537919.html
