Tuesday, 21 July 2015

Concept of string in python!

We’ll look at the two string classes from a number of viewpoints:  String slices , String methods, String Formatting.

A string is a sequence of characters. You can access the characters one at a time with the bracket operator:

>>> fruit = 'Mango'
>>> letter = fruit[1]

The second statement selects character number 1 from fruit and assigns it to letter.
>>> print letter
a

Surprised ?  you might not get what you expect.
For most people, the first letter of 'Mango' is M, not a. But for computer scientists, the index is an offset  from the beginning of the string, and the offset of the first letter is zero.


String slices : A segment of a string is called a slice. Selecting a slice is similar to selecting a character.
Let's have a example :

>>> s = 'Monty Python'
>>> print s[0:5]
Monty
>>> print s[6:12]
Python

                       

   

If you omit the first index (before the colon), the slice starts at the beginning of the string. If you omit the second index, the slice goes to the end of the string:

>>> fruit = 'banana'
>>> fruit[:3]
'ban'
>>> fruit[3:]
'ana'


String methods :
A method is similar to a function—it takes arguments and returns a value—but the syntax is different.
The Python string module provides a very robust series of methods for strings. for the entire list of
available methods, read at  http://docs.python.org/library/string.html
But we will examine  few useful methods like :
string.find()
string.replace()
string.split()

For example :
>>> name = "Rohit Saxsena"
>>> name.find('hit')
2
>>> name.replace('Rohit','Rohi')
'Rohi Saxsena'
>>> name.split()
['Rohit', 'Saxsena']
>>> name.split('a')
['Rohit S', 'xsen', '']
>>>


                                          
                            

String Formatting :
Python supports formatting values into strings. String formatting in Python uses the same syntax as the sprintf function in C.
Introducing String Formatting :
>>> a= "Hello"
>>> b= "World"
>>> "%s=%s" %(a,b)
'Hello=World'
>>>


The whole expression evaluates to a string. The first %s is replaced by the value of  a; the second %s
is replaced by the value of  b.

If you like this post or have any question, please feel free to comment!

No comments:

Post a Comment

Blogger Widget