Python Forum
Reverse string sentence with for loop?
Thread Rating:
  • 3 Vote(s) - 3.33 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Reverse string sentence with for loop?
#1
Hello, last week our class had a homework assignment in which we created a function which that capitalized all of the even words within a sentence, and reversed each odd word within a sentence. I was wondering, how would I go about using the same for loop I created to simply reverse the entire sentence itself, without capitalizing anything. 

Here is the program which I wrote for the homework assignment:


def the_sentence(words):
    sentence = words
    new_sent = sentence.split(" ")
    for x in range(len(new_sent)):
        if x % 2 == 0 :
            new_sent[x] = new_sent[x].upper()
    
        else:
            new_sent[x]=new_sent[x][::-1]
    print(new_sent)
words = input("please enter a sentence")             
the_sentence(words)
Reply
#2
Are you reversing the entire string, or just the words within the string, while those words maintain the same position?
Reply
#3
Here is a hint for you - do you know what  [::-1] does? Hint - indexing, slicing and iterations over lists have the same underlying logic. As long as you keep in mind that lists are mutable, and words are not

The last but not the least - don't iterate over range(len(smthing)), if you need index - use enumerate() function
Test everything in a Python shell (iPython, Azure Notebook, etc.)
  • Someone gave you an advice you liked? Test it - maybe the advice was actually bad.
  • Someone gave you an advice you think is bad? Test it before arguing - maybe it was good.
  • You posted a claim that something you did not test works? Be prepared to eat your hat.
Reply
#4
a hint:

In [1]: for num in range(6):
   ...:     if num & 1 == 1:
   ...:         print(num, 'odd')
   ...:     else:
   ...:         print(num, 'even')
   ...:         
   ...:         
0 even
1 odd
2 even
3 odd
4 even
5 odd
"As they say in Mexico 'dosvidaniya'. That makes two vidaniyas."
https://freedns.afraid.org
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Convert a sentence to pig latin SalsaBeanDip 4 3,197 Oct-04-2020, 01:45 AM
Last Post: SalsaBeanDip
  Adding string numbers, while loop and exit without input. Jose 11 7,459 Apr-15-2020, 08:34 AM
Last Post: Jose
  print string in reverse pseudo 5 3,505 Oct-04-2018, 08:11 PM
Last Post: buran
  write split words of sentence to file bluefrog 1 2,977 Aug-27-2018, 01:28 AM
Last Post: micseydel
  How to access each line in for loop and split string SriRajesh 2 3,132 Aug-14-2017, 06:05 PM
Last Post: tetrmnot

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020