Friday, May 6, 2011

Python Exercises - Reverse a String

As an exercise to gain more experience with Python, I wrote a function to reverse a string. Playing with ideone.com's online Python IDE was also a bonus. You can run the following code here. This is probably not the best way to solve this problem, but it works.

1
2
3
4
5
6
7
8
9
10
11
12
13
# implement a function that reverses a string
def reverse_string(in_string):
        # reverse string using brute force
        print " input is %s" % in_string
        length = len(in_string)
        out_string = ""
        for position in range(length, 0, -1):
                out_string += in_string[position-1]
        print "output is %s" % out_string
        return out_string
 
a = reverse_string("1234")
print a

2 comments:

  1. >>> text = "Hello world!"
    >>> print text[::-1]
    !dlrow olleH

    Would work too. Duck typing means strings act like lists, so list comprehension applies here. The slice syntax is [start:stop:step]; a step of -1 reverses the list.

    ReplyDelete