206k views
5 votes
write a program (using a function) that: asks the user for a long string containing multiple words. prints back the same string, except with the words in reverse order.

1 Answer

2 votes

Answer:

Explanation: Here's a Python program that uses a function to ask the user for a long string containing multiple words, and then prints back the same string with the words in reverse order:

python

Copy code

def reverse_words(string):

words = string.split()

reversed_words = words[::-1]

reversed_string = " ".join(reversed_words)

return reversed_string

user_string = input("Enter a long string containing multiple words: ")

reversed_string = reverse_words(user_string)

print("The string with words in reverse order is: ", reversed_string)

Step-by-step explanation:

The function reverse_words() takes in a string as its parameter.

The string is split into words using the split() method, which splits the string at whitespace characters and returns a list of words.

The list of words is then reversed using the slicing operator [::-1], which returns a new list with the elements in reverse order.

The reversed list of words is then joined back into a string using the join() method, with a space character as the separator.

The reversed string is returned by the function.

The user is prompted to enter a long string containing multiple words using the input() function.

The reverse_words() function is called with the user's string as its argument, and the result is stored in a variable called reversed_string.

The reversed string is printed to the console using the print() function.

SPJ11

User Barden
by
7.9k points

No related questions found