我正在尝试编写一个将输入转换为所谓的“牛拉丁语”的函数。我想从if
语句返回值,但每当我这样做时,我都会收到语法错误。我可以打印该值,但我想避免返回None
的函数。
def cow_latinify_sentence(sentence):
vowels = tuple('aeiou1234567890!@#$%^&*()-_=+|\\][}{?/.\',><`~"')
sentence = sentence.lower()
sentence_list = sentence.split()
for i in range(len(sentence_list)):
cow_word = sentence_list[i][:]
if cow_word.startswith(vowels):
print('{0}moo'.format(cow_word), end=' ')
else:
cow_word = sentence_list[i][1:] + sentence_list[i][:1]
print('{0}oo'.format(cow_word), end=' ')
cow_latin = cow_latinify_sentence("the quick red fox")
print(cow_latin)
简而言之,我如何才能将功能转移到return
而不是print
?
答案 0 :(得分:1)
def cow_latinify_sentence(sentence):
vowels = tuple('aeiou1234567890!@#$%^&*()-_=+|\\][}{?/.\',><`~"')
sentence = sentence.lower()
sentence_list = sentence.split()
result = ''
for i in range(len(sentence_list)):
cow_word = sentence_list[i][:]
if cow_word.startswith(vowels):
result += ('{0}moo'.format(cow_word) + ' ')
else:
result += '{0}oo'.format(sentence_list[i][1:] + sentence_list[i][:1]) + ' '
return result.strip()
>>> cow_latinify_sentence('hello there i am a fish')
'ellohoo heretoo imoo ammoo amoo ishfoo'
答案 1 :(得分:0)
为什么不直接替换
的两个实例print('{0}moo'.format(cow_word), end=' ')
带
return '{0}moo'.format(cow_word)+' '
你必须摆脱end=
;您不必替换原来会跟随print
输出的换行符,但如果您想在返回的字符串末尾留出空格,您仍然需要自己附加它。
答案 2 :(得分:0)
您需要创建一个列表来累积结果。
result = []
你的函数中的两个print语句需要更改为result.append(XXXX)。然后当你处理了整个句子时,你可以
return (result)
或者,将其重新形成一个句子:
return " ".join(result) + '.'
答案 3 :(得分:0)
def cow_latinify_sentence(sentence):
vowels = tuple('aeiou1234567890!@#$%^&*()-_=+|\\][}{?/.\',><`~"')
sentence = sentence.lower()
sentence_list = sentence.split()
result = ''
for i in range(len(sentence_list)):
cow_word = sentence_list[i][:]
if cow_word.startswith(vowels):
result += '{0}moo'.format(cow_word) + ' '
else:
result += '{0}oo'.format(sentence_list[i][1:] + sentence_list[i][:1]) + ' '
return result.strip()