如何用其他字母替换单词末尾的元音?
How can I replace the vowels at the end of a word by other letters?
到目前为止,这是我的解决方案:
def chemificateWord(word):
vowels = ('a', 'e', 'i', 'o', 'u', 'y','A','E','I','O','U','Y')
word2 = []
for letter in word:
if not word.endswith(vowels):
word2 = word + 'ium'
return word2
''' 所以当我现在 print(chemificateWord(Californ))
我想要的结果是:
Californ**ium**
所以我想用 'ium' 替换到最后一个结尾字母,如果它们是元音,有人可以帮忙吗? '''
def chemificateWord(word):
vowels = ('a', 'e', 'i', 'o', 'u', 'y','A','E','I','O','U','Y')
word2 = word
while word2.endswith(vowels):
word2 = word2[:-1]
word2 += "ium"
return word2
您可以通过以下方式使用 re
模块来完成此任务:
import re
def chemicate(word):
return re.sub(r'[aeriouyAEIOUY]*$', 'ium', word)
然后:
print(chemicate('Californ')) # Californium
print(chemicate('Baaa')) # Bium
re.sub
的第一个参数是所谓的模式,[]
表示里面的任何字符(本例中为元音),*
表示0次或多次重复,$
是零长度断言,表示字符串结束。
到目前为止,这是我的解决方案:
def chemificateWord(word):
vowels = ('a', 'e', 'i', 'o', 'u', 'y','A','E','I','O','U','Y')
word2 = []
for letter in word:
if not word.endswith(vowels):
word2 = word + 'ium'
return word2
''' 所以当我现在 print(chemificateWord(Californ))
我想要的结果是:
Californ**ium**
所以我想用 'ium' 替换到最后一个结尾字母,如果它们是元音,有人可以帮忙吗? '''
def chemificateWord(word):
vowels = ('a', 'e', 'i', 'o', 'u', 'y','A','E','I','O','U','Y')
word2 = word
while word2.endswith(vowels):
word2 = word2[:-1]
word2 += "ium"
return word2
您可以通过以下方式使用 re
模块来完成此任务:
import re
def chemicate(word):
return re.sub(r'[aeriouyAEIOUY]*$', 'ium', word)
然后:
print(chemicate('Californ')) # Californium
print(chemicate('Baaa')) # Bium
re.sub
的第一个参数是所谓的模式,[]
表示里面的任何字符(本例中为元音),*
表示0次或多次重复,$
是零长度断言,表示字符串结束。