Skip to main content
 首页 » 编程设计

python之使用函数将每个第二个单词替换为单词 'hello'

2025年05月04日13hnrainll

我是 Python 和编程的新手。我被要求完成一项任务,其中提出了以下问题:

创建您自己的函数,接收一个句子并将每个第二个单词替换为单词“Hello”

我的方法是将句子分成奇数和偶数单词列表,然后打印奇数列表,后面跟着单词 hello。

我尝试过这个,我所能做的就是分隔每个第二个字符而不是每个第二个单词。

对我的代码有任何想法或建议。

def replace(sentence): 
 
    l = list(sentence) 
 
    list_even = list() 
 
    list_odd = list() 
 
    index = 0 
 
    for word in l: 
        if index % 2 != 0: 
            list_even.append(word) 
        else: 
            list_odd.append(word) 
        index += 1 
 
    string_odd = "hello".join(list_odd) 
 
    print(string_odd) 

请您参考如下方法:

尽管 Jan 的回答简洁明了并且是应该使用的,但这里是一个使用您尝试过的相同方法的示例。

def replace(sentence): 
 
    l = sentence.split(' ') 
 
    list_odd = l[0::2] 
    print(list_odd) 
    final_list = [] 
 
    for word in list_odd: 
        final_list.append(word) 
        final_list.append('hello') 
 
    final_string = " ".join(final_list) 
 
    print(final_string) 
replace("I want to replace every other word in this string with hello")