指定将一个给定的字符串变成瑞典强盗语言,这意味着短语中的每个辅音都会加倍,并且中间放置一个“o”。例如,“这很有趣”将变成'tothohisos isos fofunon'。 它还需要处于“翻译”功能中。让我知道我做错了什么。请尽量简单地解释,我不是很先进:)
old_string="this is fun"
vowels=("a", "A", "e", "E", "i", "I", "o", "O", "u", "U")
def translate(old_string):
l=len(old_string)
for let in old_string[0:l]:
for vow in vowels:
if let!=vow:
print str(let)+'o'+str(let)
print translate(old_string)
我得到的输出是'tot 合计 合计 合计 合计 合计 合计 合计 合计 合计 无
答案 0 :(得分:0)
你的代码有很多循环。这是你的代码更加pythonic。
# define vowels as a single string, python allows char lookup in string
vowels = 'aAeEiIoOuU'
# do not expand vowels or spaces
do_not_expand = vowels + ' '
def translate(old_string):
# start with an empty string to build up
new_string = ''
# loop through each letter of the original string
for letter in old_string:
# check if the letter is in the 'do not expand' list
if letter in do_not_expand:
# add this letter to the new string
new_string += letter
else:
# translate this constant and add to the new string
new_string += letter + 'o' + letter
# return the newly constructed string
return new_string
print translate("this is fun")
答案 1 :(得分:-1)
试试这个:
def translate(old_string):
consonants = set("bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ")
return ''.join(map(lambda x: x+"o"+x if x in consonants else x, old_string))
工作小提琴here。
编辑:以下是您的解决方案的更正版本:
old_string="this is fun"
vowels=("a", "A", "e", "E", "i", "I", "o", "O", "u", "U")
def translate(old_string):
l=len(old_string)
translated = ""
for let in old_string[0:l]:
if let not in vowels and let != " ":
translated += let + "o" + let
else:
translated += let
return translated
print translate(old_string)
工作小提琴here。