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

2024-04-25 00:23:22 发布

您现在位置: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

Tags: of函数代码string定义def单词sentence
1条回答
网友
1楼 · 发布于 2024-04-25 00:23:22

如果pig\u拉丁函数适当地添加空格,则循环应该如下所示:

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

相关问题 更多 >