更改字符串的最后一个元素(如果它是“ e”)

时间:2019-02-03 20:38:27

标签: python string

我正在创建一个程序,将普通的英语单词转换为猪拉丁形式。我需要确定字符串是否以“ e”结尾(最后一个字符),如果是,则将其替换为“ë”。

我似乎无法使用我的功能使其正常工作。例如,在这种情况下,代码应将单词“ happy”输出为“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

2 个答案:

答案 0 :(得分:1)

您可以尝试:

your_string.endswith("e")

您还可以使用RegEx将“ e”替换为“ë”。

import re

your_string = re.sub(r"e$", "ë")

答案 1 :(得分:0)

此代码:

elvish = elvish[-1].replace('e', 'ë')

根本不执行您想要的操作。它用最后一个字母 just 重新分配elvish,并在必要时替换e。

现在,您知道在if块中最后一个字母是e,因此您始终需要替换它。然后,您要做的是获取原始字符串减去最后一个字母,然后附加ë。因此:

elvish = elvish[:-1] + 'ë'

此外,您不需要else块;您什么都不做,您可以将其删除。