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

标签 python list function str-replace find-occurrences

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

关于python - 使用函数将每个第二个单词替换为单词 'hello',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47085552/

相关文章:

c - 解释指针和 sizeof 结构的不同值

python - SSL 上的 MITM 代理卡在客户端的 wrap_socket 上

python - 将列表的值插入到mysql Python的不同列中

linux - 如何比较 2 个列表而不对文件进行排序并在输出文件中打印数据以保持其中一个文件的顺序

python - 打开多个文件中的特定行

python - 如何确定变量是否是Python中的函数?

ios - 当另一个函数结束时运行一个函数,iOS,Swift

python - 安装 setuptools 和 pip

python - 使用 Python 与 TUN\TAP for MAC OSX (Lion) 接口(interface)

python - Autodoc 继承 - 不显示来自 'Object' 的成员