【问题标题】:Write a program that takes a user input string and outputs every second word编写一个程序,接受用户输入的字符串并每隔一个单词输出一次
【发布时间】:2019-02-24 22:23:09
【问题描述】:

请输入一句话:敏捷的棕狐跳过懒狗。

输出:棕色跳狗

我一直在学习python中的字符串,但是无论我做什么,我似乎都无法编写一个程序来删除每个句子的第二个字母。

word=(input ("enter setence"))

del word[::2]

print(word[char], 
end="")

Print("\n")

这是我最接近的尝试。至少我能够在命令提示符下写出这句话,但无法获得所需的输出。

【问题讨论】:

  • 你的问题是什么?或者你认为有人会帮你做作业?
  • 我确实尝试过这个问题,但我无法得到解决方案,我研究了 python 中的字符串,但我仍然无法得到答案。所以我只是需要别人帮助我做错了什么,并从我的错误中吸取教训。

标签: python string output word


【解决方案1】:
string = 'The quick brown fox jumps over the lazy dog.'
even_words = string.split(' ')[::2]

您使用空格分割原始字符串,然后使用 [::2] 拼接从中取出所有其他单词。

【讨论】:

【解决方案2】:

尝试类似:

" ".join(c for c in word.split(" ")[::2])

【讨论】:

    【解决方案3】:

    试试这个:

    sentenceInput=(input ("Please enter sentence: "))
    
    # Function for deleting every 2nd word
    def wordDelete(sentence):
    
        # Splitting sentence into pieces by thinking they're seperated by space.
        # Comma and other signs are kept.
        sentenceList = sentence.split(" ")
    
        # Checking if sentence contains more than 1 word seperated and only then remove the word
        if len(sentenceList) > 1:
            sentenceList.remove(sentenceList[1])
    
        # If not raise the exception
        else:
            print("Entered sentence does not contain two words.")
            raise Exception
    
        # Re-joining sentence
        droppedSentence = ' '.join(sentenceList)
    
        # Returning the result
        return droppedSentence
    
    wordDelete(sentenceInput)
    

    【讨论】:

      【解决方案4】:

      尝试类似的方法。

      sentence = input("enter sentence: ") words = sentence.split(' ') print(words[::2])

      【讨论】:

      • 试过了吗?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-13
      • 1970-01-01
      • 1970-01-01
      • 2018-05-23
      相关资源
      最近更新 更多