Reputation: 19
I am trying to create a function that reverses a sentence that a user inputs but when I run the program I am not getting the sentence in reverse. Bellow is my code
sentence=input('Enter a sentence: ')
def sentence_reverse(sentence):
words=sentence.split()
newsentence=words.reverse()
return (newsentence)
print(sentence_reverse(sentence))
Upvotes: 0
Views: 69
Reputation: 2521
Welcome to StackOverflow!
The reason is because you are using split()
but it does not convert your input string into the list of its character. It just make a list with one element, which is your input string. Instead, convert the string to list using list()
function, and then convert it back to string using join()
function. In addition to that, reverse()
returns nothing. So, you have to returns the words
variable instead.
sentence=input('Enter a sentence: ')
def sentence_reverse(sentence):
words=list(sentence)
words.reverse()
return ''.join(words)
print(sentence_reverse(sentence))
Upvotes: 0
Reputation: 896
Here is a simplest way to solve your problem:
sentence=input('Enter a sentence: ')
def sentence_reverse(sentence):
words= sentence.split() # breaks the sentence into words
rev_sentence= ''
for word in words:
rev_sentence = ' ' + word + rev_sentence
return rev_sentence
print(sentence_reverse(sentence))
Input: Hi please reverse me
Ouput: me reverse please Hi
Hope this helps you. Kindly let me know if anything else is needed.
Upvotes: 0
Reputation: 226
def sentence_reverse(s):
return ' '.join(s.split()[::-1])
print(sentence_reverse(sentence))
Upvotes: 1
Reputation: 6441
reverse()
is an in-place operation, meaning it reverses words
itself and doesnt return anything. So instead of returning newsentence
, you want to return words
like so:
sentence=input('Enter a sentence: ')
def sentence_reverse(sentence):
words=sentence.split()
words.reverse()
return words
print(sentence_reverse(sentence))
>>>Enter a sentence: hello world
>>>['world', 'hello']
Upvotes: 0
Reputation: 226
you can do this
def reverse(s):
if len(s) == 0:
return s
else:
return reverse(s[1:]) + s[0]
or :
def reverse2(s):
return s[::-1]
Upvotes: 0