我是一个蟒蛇新手,我似乎遇到了问题,我看不出我做错了什么。我试图让它成为当我输入一个字符串时它将字符串变成猪拉丁语。问题在于,当我这样做时,它只打印出转换后的字符串中的第一个单词。有人能指出我正确的方向吗?
干杯
def pig_latin(data):
words = data.split()
piglatin = []
vowels = ["a", "i", "e", "u", "o", "1", "2", "3", "4", "5", "6",
"7", "8", "9", "0"]
for word in words:
if word[0] in vowels:
word = word + "way"
else:
word = word.replace(word[0],"") + word[0] + "ay"
word = word.lower()
piglatin.append(word)
piglatin = "".join(piglatin)
return piglatin
答案 0 :(得分:0)
由于缩进不良,您的return
语句位于for
循环内,所以很明显它会在一次迭代后返回。
以下是修复此问题的代码以及其他一些更改:
def pigetize(text, wovels):
return ((text + "way") if text[0] in wovels else (text[1:]+text[0]+"ay")).lower()
def pig_latin(data):
words = data.split()
piglatin = []
vowels = ["a", "i", "e", "u", "o"] + [str(x) for x in range(10)]
for word in words:
piglatin.append(pigetize(word, wovels))
return "".join(piglatin)
答案 1 :(得分:0)
检查缩进。你的return语句在for循环中,所以它会在第一次迭代后返回。您希望确保return
与for
语句处于同一缩进级别。
def pig_latin(data):
words = data.split()
piglatin = []
vowels = ["a", "i", "e", "u", "o", "1", "2", "3", "4", "5", "6", "7", "8", "9", "0"]
for word in words:
if word[0] in vowels:
word = word + "way"
else:
word = word.replace(word[0],"") + word[0] + "ay"
word = word.lower()
piglatin.append(word)
piglatin = " ".join(piglatin)
return piglatin