编写一个程序,该程序接受用户输入的字符串并输出第二个单词

时间:2019-02-24 22:23:10

标签: python string output word

请输入一个句子:敏捷的褐狐狸跳过了懒狗。

输出:棕色跳狗

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

A

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

4 个答案:

答案 0 :(得分:3)

string = 'The quick brown fox jumps over the lazy dog.'
even_words = string.split(' ')[::2]

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

答案 1 :(得分:0)

尝试类似的东西:

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

答案 2 :(得分:0)

尝试一下:

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)

答案 3 :(得分:0)

尝试类似的事情。

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