Python Forum

Full Version: Reverse string sentence with for loop?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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)
Are you reversing the entire string, or just the words within the string, while those words maintain the same position?
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
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