2017-01-09 48 views
0

指定将给定的字符串转换为瑞典强盗语言,这意味着短语中的每个辅音都加上了一个“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 TOT TOT TOT TOT TOT TOT TOT TOT TOT 无

回答

-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

+0

嘿谢谢,但我不知道什么地图和lambda是。你能简化一下吗?它可以,如果它需要更多的线路。谢谢! – Addison

+1

你确实意识到这是一个完全不同的解决方案,对吧?而且你引入了更先进的概念?这不是对这个问题的回答。这是“你的”对初始问题的回答。 –

+0

@Addison'map'将一个函数映射到一个集合上,'lambda'允许您创建匿名函数(例如,不绑定到名称的函数)。你可以阅读更多关于'lambda'函数[这里](http://www.secnetix.de/olli/Python/lambda_functions.hawk)。 –

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")