我创建一个普通的英语单词转换成猪拉丁形式的程序。我需要能够确定是否在字符串中的“E”结束(最后一个字符),如果确实如此,随着电子取代它。
我似乎无法能够得到它通过我的功能工作。例如,应输出“快乐”为‘appyhë’通过该条件的结束的代码。
# User Input: Ask user for a word
WordToBeTranslated = input("Please enter a word in English: ")
WordToBeTranslatedLower = WordToBeTranslated.lower()
# Condition #1: Moving the First Letter to the end
elvish = WordToBeTranslatedLower[1:] + WordToBeTranslatedLower[0]
print(elvish)
# Condition #2 + #3: Appending a Vowel / Appending 'en' to the end of a word
vowel = ['a', 'e', 'e', 'i', 'o', 'u']
import random
randomVowel = random.choice(vowel)
list = []
list.append(WordToBeTranslated)
if len(WordToBeTranslated) > 4:
elvish += randomVowel
else:
elvish = elvish + 'en'
# Condition #4: change all k's to c's
elvish = elvish.replace('k', 'c')
print(elvish)
# Condition #5: Replace 'e' at end of the word with ë
if elvish[-1] == 'e':
elvish = elvish[-1].replace('e', 'ë')
else:
elvish = elvish
你可以试试:
your_string.endswith("e")
您还可以使用正则表达式来替代“E”与“E”。
import re
your_string = re.sub(r"e$", "ë")
此代码:
elvish = elvish[-1].replace('e', 'ë')
根本不会做你想做的。它重新分配elvish
只有最后一个字母,更换电子如果有必要。
现在,你知道这一点,如果块的最后一个字母是e里面,所以你总是需要更换。你想要做的又是什么把原来的串减去最后一个字母,并追加ë
。所以:
elvish = elvish[:-1] + 'ë'
此外,你并不需要一个else块;你什么也不做,你可以将其删除。