s

Problem6



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


sentence = str(input("Please enter a sentence: "))

words = sentence.split()  

num_words = len(words)  


other_word = words[::2] 

print (" ".join(other_word)) 

This program asks the user input a string and it will output every second word. It takes a string input by the user, then splits the string into words. A word here it taken as one or more characters separated by a space. Go through the list of words but only print every second one. It does so using indexing to go through each word in the list of words starting from the very first word, ending at the very last word, using a step size of 2 to get every second word. It then concatenate every second word in other_word with whitespace using the str.join() method.

Python logo

Tech used:
  • Python
  • .split
  • .join