-2
p_phrase = "was it a car or a cat I saw"

p = p_phrase.split()

p.reverse()

print(p_phrase)

r_phrase = ""

for words in p:

    if p_phrase != r_phrase + words[:-1]+"":
    
    print(r_phrase)    
    


    

I wrote the following code to reverse the string p_phrase but the output is "was it a car or a cat I saw". I don't understand how this output is given. The output I want to achieve is "was I tac a ro rac a ti saw". Can you help me?

  • 5
    Does this answer your question? [Reverse a string in Python](https://stackoverflow.com/questions/931092/reverse-a-string-in-python) – itprorh66 Dec 23 '20 at 18:47
  • `p.reverse()` reverses a list, not a string, and returns it, not reverses in place. `words[:-1]` is correct if you add another colon, but why do you need to reverse individual words? – OneCricketeer Dec 23 '20 at 18:55
  • Because the exercise I am doing wants me to do it that way. – Python programmer Dec 23 '20 at 18:58

1 Answers1

0

To reverse a string use the slice capability like:

p_phrase = "was it a car or a cat I saw"
print(p_phrase[::-1]  

Yields:

'was I tac a ro rac a ti saw'
itprorh66
  • 3,110
  • 4
  • 9
  • 21