Tuesday, 28 June 2011

Python : Interesting String & List

Here i would like to share some interesting behavior of String & List when you use python interpreter.


We all know that the fundamental thing about Python Strings is that they are "Immutable" ,once you created a string you couldn't change it. See some examples....

>>> s = 'fun with string'
>>> s
'fun with string'

you can just add another string by using  '+'  as shown below...

>>> s + '!!!!'
'fun with string!!!!'

Another important feature is String Slices. Just see how "slice" syntax behaves in python.

>>> s = 'fun with string'
>>> s[0]                                                 
>>> s[1:4]
'un '
>>> s[1:]
'un with string'
>>> s[:]
'fun with string'
>>> s[-1]
>>> s[-4]
>>> s[:-3]
'fun with str'
>>> s[-3:]

So now we have a string 's' and we can apply all the methods (i.e functions) that are related to string to 's' as shown below...

>>> s.upper()
>>> s.lower()
'fun with string'
>>> s.startswith('fun')
>>> s.endswith('string')
>>> s.replace('string','python')
'fun with python'

But my favorite is the method called ' s.split() '. Just see what happens if i assigned s.split() function in to a variable 's' itself. If we print it you can see a list of elements.It just transformed into a list.

>>> s = s.split()
>>> s
['fun', 'with', 'string']


So now the variable 's' will behave like  a list.Now you can apply all the methods related to list here with 's'.

>>> s.append('& list')
>>> s
['fun', 'with', 'string', '& list'] 
>>> s.insert(0,'some')
>>> s
['some', 'fun', 'with', 'string', '& list']
>>> s.index('some')
>>> s.index('string')
>>> s.sort()
>>> s
['& list', 'fun', 'some', 'string', 'with']
>>> s.pop(0)
'& list'

See what happens if i call the function " join() ",and assigned it to same variable 's' .When you print 's' you could see the first string.Is it interesting?

>>> s = ['fun', 'with', 'string', '& list']
>>> s = ' '.join(s)
>>> s

'fun with string & list'

Thank You....

No comments:

Post a Comment