如何操作数组中的字符串?

时间:2016-10-26 13:00:38

标签: python

我试图在一个句子上运行一个先前定义的函数,而且我已经分到了单词串,但是我无法弄清楚如何对它进行循环。请帮忙。代码如下。

def pig_latin_sentence(sentence):
    ''' Converts a string of words separated by spaces to Pig Latin'''
    words=sentence.split(" ")
    for
        pig_latin(word)
        sentence2=sentence2+word
return sentence2

1 个答案:

答案 0 :(得分:-1)

如果pig_latin函数适当地添加空格::

,循环应该看起来像这样
def pig_latin_sentence(sentence):
    ''' Converts a string of words separated by spaces to Pig Latin'''
    words=sentence.split(" ")
    for word in words:
        pig_latin(word)
        sentence2=sentence2+word
return sentence2

但如果没有,那么也许像这样使用join并避免使用map函数的for循环会更好:

def pig_latin_sentence(sentence):
    ''' Converts a string of words separated by spaces to Pig Latin'''
    return ' '.join( map( pig_latin, sentence.split() ) )
相关问题