我正在试着把字符串转换成拉丁。大多数在线示例都没有考虑到,如果一个单词以多个辅音开头,则必须将所有辅音移动到末尾(school --> oolschay)。我的版本目前正在处理第一个字母是元音,以及抓取那些不是以元音开头的单词,然而,我不知道如何阻止它抓取单词中的每个元音实例,而不仅仅是第一个实例。
代码如下:
pigLatin = input("Convert message to pig latin: ")
wordList = pigLatin.lower().split(" ")
vowels = ['a', 'e', 'i', 'o', 'u']
pigLatin = []
eachWord = []
for word in wordList:
if word[0] in 'aeiou': #case where vowel is first
pigLatin.append(word + 'yay')
if word[0] not in 'aeiou':
for letter in word:
if letter in 'aeiou':
pigLatin.append(word[word.index(letter):] + word[:word.index(letter)] +'ay')
print(" ".join(pigLatin))
发布于 2018-07-25 07:11:44
您可以在内部的for循环中添加一条break
语句,该循环遍历每个单词。一旦你找到一个元音,它就会跳出循环。或者至少我认为这就是你遇到的问题(你的问题有点令人困惑)。
试试这个:
pigLatin = input("Convert message to pig latin: ")
wordList = pigLatin.lower().split(" ")
vowels = ['a', 'e', 'i', 'o', 'u']
pigLatin = []
eachWord = []
for word in wordList:
if word[0] in 'aeiou': #case where vowel is first
pigLatin.append(word + 'yay')
else:
for letter in word:
if letter in 'aeiou':
pigLatin.append(word[word.index(letter):] + word[:word.index(letter)] +'ay')
break
print(" ".join(pigLatin))
通过使用else
代替if word[0] not in 'aeiou':
,我还改进了您的代码风格
快乐编码!
https://stackoverflow.com/questions/51508664
复制相似问题