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 stringdef reverse_string(in_string):
# reverse string using brute forceprint" input is %s"% in_string
length = len(in_string)
out_string = ""for position inrange(length, 0, -1):
out_string += in_string[position-1]print"output is %s"% out_string
return out_string
a = reverse_string("1234")print a
>>> 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.
>>> text = "Hello world!"
ReplyDelete>>> 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.
That is a much better solution!
Delete