Monday, July 24, 2017

6 different ways to reverse a string in Python

A lot of interviewers seem to have a fascination for this often asked question :

"How to reverse a string in Python ?"

There are of course, many possible answers for this. Here are some that might come in handy for your understanding and learning.

1. Old School while loop method

>>> x = "hello"
>>> idx = len(x)
>>> rev = list()
>>> while idx > 0:
...         rev.append( x[idx-1] )
...         idx -= 1
...
>>> print ''.join(rev)
olleh

2. Using Python's reversed function with a for loop


Monday, July 17, 2017

The Curious Case of Python String Slicing

We were studying about Python strings and we tried to understand Python String Slicing through an example. We found a very strange [at least at first look] result when we tried to use String Slicing for creating a copy of the string.

To better understand the scenario and the result, lets start with the basics of integers and lists w.r.t to slicing.

>>> m = 10         # Integer m initialised to 10
>>> n = m           # Another integer n storing the same value as in m
>>> print m, n
10 10

>>> id(m), id(n)
( 140204825415168 , 140204825415168 ) # <-- Both are of the same id
A variable name in Python, is a "tag" name associated with a memory location.
In the above scenario, when we initialised variable m, Python associated a tag name m with memory location [ 140204825415168 ] ( For this discussion, assume that id represents memory location )