gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 07:31:20 27 4
gpt4 key购买 nike

我是 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com