Home > python > Reverse a string

Reverse a string

Exercise #1: Take a string and reverse its characters. For instance “ab12” => “21ba”.


#!/usr/bin/env python

s = 'Python adventures'
print s         # Python adventures
print s[::-1]   # serutnevda nohtyP

Slice notation has the form [start:stop:step]. By default, start is at the beginning of a sequence, stop is at the end, and step is 1. So the slice [::-1] returns the full sequence in reverse order.

Exercise #2: Decide if a word is a palindrome.


#!/usr/bin/env python

def is_palindrome(str):
    return str == str[::-1]

print is_palindrome('1367631')      # True
print is_palindrome('Python')       # False
Categories: python Tags: , , ,
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: