简体   繁体   中英

Write a program that takes a user input string and outputs every second word

Please enter a sentence: The quick brown fox jumps over the lazy dog.

Output: The brown jumps the dog

I've been doing some learning in strings in python, but no matter what I do, I can't seem to write a program that will remove the 2nd letter of every sentence.

word=(input ("enter setence"))

del word[::2]

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

Print("\n")

This was my closest attempt. At least I was able to write the sentence on the command prompt but was unable to get the required output.

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

You split the original string using spaces, then you take every other word from it with the [::2] splice.

尝试类似的东西:

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

Try this:

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)

尝试类似的事情。

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM