Python3 reversing an inputed sentence - python-3.x

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))

def sentence_reverse(s):
return ' '.join(s.split()[::-1])
print(sentence_reverse(sentence))

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]

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']

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.

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))

Related

How would I print a string obtained from a user in reverse?

I'm stuck on an exercise where I must obtain a string from a user and then print it in reverse with each letter on its own line. I've done this successfully with a for loop but I was wondering how to do so without it.
user_string = input("Please enter a string: ")
for letter in (user_string)[::-1]:
print(letter)
You can reverse and use str.join to rebuild the string.
print("\n".join(reversed(input("Please enter a string: "))))
If you know how many characters there are in the string or array (calculate using the length method len()) then you could do:
while i < arr_length:
with i incrementing at the end of every round.
The rest of the code would be the same but using i as an index.
One method would be to cast the string to a list and use the list.pop() method until there are no characters left in the list.
user_input = list(input())
while len(user_input) > 0:
print(user_input.pop())
list.pop() will remove the last item in the list and return it.
def reverse(s):
str = ""
for i in s:
str = i + str
return str
s = "Geeksforgeeks"
print("The original string is : ", end="")
print(s)
print("The reversed string(using loops) is : ", end="")
print(reverse(s))
Using index property we can easily reverse a given string
a = input()
print(a[::-1])

In python 3 how can I return a variable to a function properly?

I am currently in school studying python and have a question. I am working on a midterm project that has to take an input, assign it to a list, if the first letter isnt capital - capitalize it..and count the number of words in the sentence.
While my code works.. I can't help but think I handled the arguments into the functions completely wrong. If you could take a look at it and help me out on how I could clean it up that would be excellent.
Please remember - I am new..so explain it like I am 5!
sentence_list = sentList()
sentence = listToString(sentence_list)
sentence = is_cap(sentence)
sentence = fix(sentence)
sentence = count_words(sentence)
def sentList():
sentence_list = []
sentence_list.append(input('Please enter a sentence: '))
return sentence_list
def listToString(sentence_list):
sentence = ""
sentence = ''.join(sentence_list)
return sentence
def is_cap(sentence):
sentence = sentence.capitalize()
return sentence
def fix(sentence):
sentence = sentence + "." if (not sentence.endswith('.')) and (not sentence.endswith('!')) and \
(not sentence.endswith('?')) else sentence
return sentence
def count_words(sentence):
count = len(sentence.split())
print('The number of words in the string are: '+ str(count))
print(sentence)
main()```
first of all, your code is very good as a beginner, good job dude.
so
to make your function run, you need call it after you defined them. but here you put the call at the top of the page.
the reason of that is python read the codes from top to bottom, so when he read the first that call a function that he didn't read 'til this line
the code should be like this:
def sentList():
sentence_list = []
sentence_list.append(input('Please enter a sentence: '))
return sentence_list
def listToString(sentence_list):
sentence = ""
sentence = ''.join(sentence_list)
return sentence
def is_cap(sentence):
sentence = sentence.capitalize()
return sentence
def fix(sentence):
sentence = sentence + "." if (not sentence.endswith('.')) and (not sentence.endswith('!')) and \ (not sentence.endswith('?')) else sentence
return sentence
def count_words(sentence):
count = len(sentence.split())
print('The number of words in the string are: '+ str(count))
print(sentence)
sentence_list = sentList()
sentence = listToString(sentence_list)
sentence = is_cap(sentence)
sentence = fix(sentence)
sentence = count_words(sentence)
I guess that it. if you have any another question. this community will always be here

Why is my recursive function is not concatenatening string?

I am writing a recursive function to print a string backwards. I am wondering why my string formatting of the return statement is not working? I am using python 3.7.
It would be very helpful if someone please can tell me why I can not write a recursive function like following?
def back(word):
if len(word)>1:
print (word[-1] + (back(word[:len(word)-1])), end="")
elif len(word)==1:
return word
else:
print ("end")
back("stack")
As khelwood mentioned in the comments, doing a print() is not a substitute for return.
The fix for your problem is:
def back(word):
ln = len(word)
if ln >1:
wmo = word[-1]
# Changed print() to return
return (wmo + (back(word[:len(word)-1])))
elif ln ==1:
return word
else:
print ("end")
# Changed to print() the returned values from function
print(back("stack"))
As you can see above, in the fixed solution, we are returning the value from function and printing it outside.
Hope this helps!

Write a function that removes all occurrences of a given letter from a string [duplicate]

This question already has answers here:
Strange result when removing item from a list while iterating over it
(8 answers)
Closed 3 years ago.
Write a function that removes all occurrences of a given letter from a string:
remove_letter("a", "apple") == "pple"
remove_letter("a", "banana") == "bnn"
remove_letter("z", "banana") == "banana"
I have tried to make a list from the string and then deleting the element. Below is my code for this problem. Is this correct? Or should I think of something else? Can you tell a better method than this and why is that method better?
def rmv(word, letter):
word = list(word)
for ele in word:
if ele == letter:
word.remove(ele)
print(word)
This code does not show any error messages. It gives the expected output for the words like "banana" but for word like "bananna" it would not give the expected output.
For rmv("banana", "n") output is "baaa".
For rmv("bananna", "n") output is "baana".
Your code approach with fix:
def rmv(word, letter):
word = list(word)
newWord=[]
for i in range(len(word)):
if word[i]!= letter:
newWord.append(word[i])
print(newWord)
rmv("bananna", "n")
What you were doing wrong:
You were iterating your list and deleting as and when your if-else met the condition:
if ele == letter:
word.remove(ele)
But the problem with this approach is that your pointer moves ahead and the deletion causes the list to shift accordingly at the same time and so when you see the case of
rmv("bananna", "n")
By the time pointer could get the opportunity to scan and remove the last n the list caused it to shift at an index that was already scanned by your list and hence it got ignored.
On a side note -
I generally advise people to use Python-tutor to debug their code. It's GUI based code visualizations helps to know where you went wrong.
Your problem is that you modify (remove) a list while you iterate over it. Just put a few print lines into your code to see what it does.
It's better to create a new list and adding only characters that you want to keep:
def rmv(word, letter):
out = []
for char in word:
if char != letter:
out.append(char)
return ''.join(out)
or, even more compactly:
def rmv(word, letter):
return ''.join(char for char in word if char != letter)
Why not just:
def rmv(word, letter):
return word.replace(letter, '')
print(rmv("apple", "a"))
There is no need for you to iterate through each character of the string when one function call will do it for you.
Why don't you try the string replace function?
Try this code:
def rmv(word, letter):
return word.replace(letter, "")

converting individual characters in string to uppercase

my code
name='helloworld'
i=0
while(i<len(name)):
name[i].upper()
i=i+2
print(i)
print(name)
want the output as 'AnThRoPoMoRpHiSm'. Please help.
You can enumerate your string and capitalize one of every 2 letters, then join the result:
name='anthropomorphism'
''.join([s if i%2 else s.upper() for i,s in enumerate(name)])
This returns:
'AnThRoPoMoRpHiSm'

Resources