Archive

Posts Tagged ‘slice’

Reverse a string

September 23, 2010 Leave a comment

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

Solution:

#!/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.

Solution:

#!/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: , , ,