I would like to reverse a sentence. I have this:

sentence = "a doctor kills your ills with pills and you with bills"
 
print sentence[::-1]
# sllib htiw uoy dna sllip htiw slli ruoy sllik rotcod a

However, I would like the sentence reversed like this:
bills with you and pills with ills your kills doctor a

Split up the sentence into an array using spaces as your separator. Then reverse that array and print them out.

In Python these kind of things are a lot easier than in C#. Here is a typical example ...

sentence = 'the dog barks'
 
# create a list of words (default=whitespaces)
words = sentence.split()
 
# take a look
print words  # ['the', 'dog', 'barks']
 
# now reverse the list of words
rev_words = reversed(words)
 
# join the reversed list to a sentence again (' '=space)
rev_sentence = ' '.join(rev_words)
 
# look at rev_sentence
print rev_sentence  # barks dog the
 
# you can do that all on one line
print ' '.join(reversed(sentence.split()))
commented: What would we beginner python programmers do without you? +2

another way

>>> for i in range(len(sentence.split()),0,-1):
...  print sentence.split()[i-1],

Thanks for the ideas gentle people!

Those >>> and ... int the code confuse me, so I rewrote it to regular code:

sentence = "a doctor kills your ills with pills and you with bills"
rev_sentence = ""
for i in range(len(sentence.split()),0,-1):
    rev_sentence += sentence.split()[i-1] + " "
    
print rev_sentence  
"""
bills with you and pills with ills your kills doctor a
"""

As you see, it works.

Looks like you are catching on quickly!

You might find yourself liking Python as much as you do C#. Just want to point out that there is also a language called "Boo" with a Python syntax that feeds right into C#, using the same compiler and the .NET or Mono environment. This way you can produce rather tight executable (.exe) files. Check out "A Taste of Boo" at:
http://www.daniweb.com/code/snippet429.html

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.