【问题标题】:replace every second word with the word 'hello' using a function使用函数将每隔一个单词替换为单词“hello”
【发布时间】:2018-04-15 13:58:43
【问题描述】:

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

【问题讨论】:

  • @prune 编辑很好 - 无需添加作业内容 - 这与问题无关
  • 尝试str.split() 将句子拆分为单词。当您的程序出错时,有时打印一些内容以确保它按照您的想法进行操作会很有帮助。

标签: python list function str-replace find-occurrences


【解决方案1】:

使用列表推导:

string = "Create your own function that takes in a sentence and replaces every second word with the word “Hello”"

hello = " ".join(["{} hello".format(word) 
        for idx, word in enumerate(string.split()) 
        if idx % 2 == 0])
print(hello)
# Create hello own hello that hello in hello sentence hello replaces hello second hello with hello word hello

这里的重点是使用enumerate() 函数和模运算符(%)。


正如@darksky 在评论部分指出的那样,这在尝试学习Python 时可能很难掌握。相反,您可以很好地使用更长的功能,例如
lst = []
for idx, word in enumerate(string.split()):
    if idx % 2 == 0:
        lst.append(word)
        lst.append("hello")

words = " ".join(lst)
print(words)

打印出来的完全一样。

【讨论】:

  • 使用 formatenumerate 之类的东西可能会节省一些代码行,但这很丑陋,并且不会帮助不熟悉该语言的人立即理解代码的底层机制。我建议使用更简单的 for 循环和基本的索引计数器。
  • @darksky:那就去吧:)
  • @darksky:已更新。
  • 谢谢。这对初学者更友好。
【解决方案2】:

虽然 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")

【讨论】:

    【解决方案3】:

    两个简单的更改将保存您给定的代码。首先,您要逐步检查输入句子的单词,而不是单个元素(字符)。删除l = list(sentence) 行,因为这会将您的输入分成字符。相反,split 空格处的列表(默认)。

       for word in sentence.split():
    

    这将为您提供如下输出:

    Thishellogivehellooutput
    

    现在,只需在您的 join 命令中添加空格:

        string_odd = " hello ".join(list_odd)
    

    获得:

    This hello give hello output
    

    现在,您还有一个问题:对于偶数个单词的句子,您缺少最后一个“你好”。我会让你处理这个问题,因为你已经知道如何使用模数命令了。您可能希望恢复原始输入保存

    l = sentence.split()
    for word in l:
    

    还请注意,您可以完全删除list_even;你在浪费精力,因为你从不使用它。你可以忽略这些话。

    【讨论】:

      【解决方案4】:

      您可能会发现这更容易理解。您可以简单地创建一个新的句子对象并用单词填充它。

      sentence = "Im new to python and programming."
      new_sentence = ""
      
      index = 0
      
      for word in sentence.split():
      
          if index % 2 == 1:
              new_sentence += "hello "
          else:
              new_sentence += word + " "
      
          index += 1
      
      # remove the last space at the end
      sentence = sentence[:-1]
      
      print(new_sentence)
      

      【讨论】:

        【解决方案5】:
        def sentenceReplace(sentence):
            sentence_list = sentence.split()
            for counter, word in enumerate(sentence_list):
                if counter % 2 == 0:
                    sentence_list[counter] = "Hello"
            new_sentence = " ".join(sentence_list)   
            print(new_sentence)
        
        sentenceReplace(input("Say Something here!"))
        

        接受句子。使用 split 方法创建一个列表。然后使用创建计数器的 enumerate 遍历列表。

        如果计数器的余数(从枚举生成)为 0,则替换该索引处的单词。

        函数结束后需要再次加入列表并打印出来

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-04-16
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-09-01
          相关资源
          最近更新 更多