Author name: Prasanna

Python Programming – Simple and Compound Statements

In this Page, We are Providing Python Programming – Simple and Compound Statements. Students can visit for more Detail and Explanation of Python Handwritten Notes Pdf.

Python Programming – Simple and Compound Statements

A statement is a unit of code that the Python interpreter can execute. A script usually contains a sequence of statements.

A namespace is a logical grouping of the objects used within a program. Most namespaces are currently implemented as Python dictionaries. Examples of namespaces are the set of built-in names (containing functions such as abs ( ), and built-in exception names), the global names in a module, and the local names in a function definition.

The important thing to know about namespace is that there is absolutely no relation between names in different namespaces. For instance, the functions ____built-in______.open ( ) and os . open ( ) are distinguished by their namespaces. The following is an example of the local namespace.

>>> def example ( arg ) :
. . .       x=4
. . .       print locals ( )
. . . 
>>> example ( 10 )
{ ' x ' : 4 , ' arg ' : 10 }
>>> example ( ' hello ' )
{ ' x ' : 4 , ' arg ' : ' hello ' }

The function example ( ) has two variables in its local namespace: arg, whose value is passed into the function, and x, which is defined within the function. The locals ( ) built-in function return a dictionary of name-value pairs; the keys of this dictionary are the names of local variables as strings; the values of the dictionary are the actual values of the variables.

Python Programming – Simple and Compound Statements Read More »

Python Programming – Compound statement Built-in functions

In this Page, We are Providing Python Programming – Compound statement Built-in functions. Students can visit for more Detail and Explanation of Python Handwritten Notes Pdf.

Python Programming – Compound statement Built-in functions

Built-in functions

Till now, the discussed functions need to be defined before using it in a program; such functions are called user-defined functions. Python has a number of functions that are always available. These are called built-in functions. They are listed here in alphabetical order.

                   abs ( )                                  all ( )                                          any ( )
                   basestring ( )                       bin ( )                                        bool ( )
                   bytearray ( )                        callable ( )                                 chr ( )
                   classmethod ( )                   cmp ( )                                       compile ( )
                   complex ( )                          delattr ( )                                    diet ( )
                   dir ( )                                   divmod ( )                                  enumerate ( )
                  eval ( )                                  execfile ( )                                   file ( )
                  filter ( )                                float ( )                                      format ( )
                  frozenset ( )                        getattr ( )                                   globals ( )
                  hasattr ( )                            hash ( )                                         help ( )
                  hex ( )                                 id ( )                                            input ( )
                  int ( )                                  isinstance ( )                             issubclass ( )
                  iter ( )                                  len ( )                                         list ( )
                  locals ( )                             long ( )                                         map ( )
                  max ( )                               memoryview ( )                            min ( )
                  next ( )                              object ( )                                        oct ( )
                 open ( )                              ord ( )                                           pow ( )
                 print ( )                            property ( )                                      range ( )
                raw_input ( )                      reduce ( )                                     reload ( )
                repr ( )                              reversed ( )                                   round ( )
                set ( )                                setattr ( )                                        slice ( )
               sorted ( )                           staticmethod ( )                              str ( )
               sum ( )                               super ( )                                         tuple ( )
               type ( )                               unichr ( )                                       Unicode ( )
               vars ( )                              xrange ( )                                        zip ( )
             import ( )                           apply ( )                                         buffer ( )
              coerce ( )                          intern ( )

Some of the above built-in functions are discussed below:

abs ( x )
Return the absolute value of a number. The argument may be a plain or long integer or a floating-point number. If the argument is a complex number, its magnitude is returned.

>>> abs ( - 34 )
34 
>>> abs ( 34 . 5 )
34 . 5
>>> abs ( -3 -4 j )
5 . 0

all ( iterable )
Return True, if all elements of the iterable are true (or if the iterable is empty).

>>> all ( [ True , 10 ] )
True
>>> all ( [ True , 10 , 0 ] )
False
>>> all ( ( ) )
True

any ( iterable )
Return True, if any element of the iterable is true. If the iterable is empty, return False.

>>> any ( [ 0 , 5 , -3 ] )
True
>>> any (  [0 , False  , -3 ] )
True
>>> any ( ( ) )
False

bin ( x )
Convert an integer number to a binary string.

>>> bin ( 8 )
' 0b1000 '
>>> bin ( 27 )
' 0b11011 '
>>> (27) . hit_length ( )
5
>>> bin ( -1327 )
' -0b100101111 '
>>> ( -1327 ) . bit_length ( )
11

bool ( [ x ] )
Convert a value to a boolean. If x is false or omitted, this returns False; otherwise, it returns True. If no argument is given, this function returns False.

>>> bool ( 5 )
True 
>>> bool ( -5 )
True
>>> bool ( 0 )
False 
>>> bool ( ' hi ' )
True
>>> bool ( )
False 
>>> bool ( '' )
False 
>>> bool ( None )
False
>>> bool ( ' \ n ' ) 
True
>>> bool ( [ 0 ] )
True
>>> bool ( ( None , ) ) 
True

chr ( i )
Return a string of one character whose ASCII-8 code is the integer i. This is the inverse of ord ( ). The argument must be in the range [0,255]; ValueError will be raised if i is outside that range.

>>> for i in range ( 33 , 95 ) : print i , ' =  ' , chr ( i )
. . . 
33 = !
34 = "
35 = #
36 = $
3 7 = %
38 = &
39 = '
40 = (
41 = )
42 = *
43 = +
44 = ,
45 = -
46 = .
47 = /
48 = 0 
49 = 1
50 = 2
51 = 3
52 = 4
53 = 5 
55 = 7
56 = 8
57 = 9
58 = :
59 = ;
60 = < 
61 = = 
62 = >
63 = ?
64 = 0
65 = A
66 = B
67 = C
68 = D
69 = E
70 = F
71 = G
72 = H
73 = I
74 = J
75 = K
76 = L
77 = M
78 = N
79 = O
80 = P
81 = Q
82 = R
83 = S
84 = T
85 = U
86 = V
87 = W
88 = X
89 = Y
90 = Z
91 = [
92 = \
93 = ]
94 = A

cmp ( x , y )
Compare the two objects x and y, and return an integer according to the outcome. The returned value is negative, if xc’y, zero, if x==y, and strictly positive, if x>y.

>>> cmp ( 2 . 5 , 5 . 2 )
-1 
>>> cmp ( 5 . 2 , 5 . 2 )
0 
>>> cmp ( 5 . 2 , 2 . 5 ) 
1
>>> cmp ( ' hi ' , ' hello ’ )
1
>>> cmp ( 'hello ' , ' hi ' )
-1

complex ( [ real [ , imag ] ] )
Create a complex number with the value real+imag* j, or convert a string or number to a complex number. If the first parameter is a string, it will be interpreted as a complex number and the function must be called without a second parameter. The second parameter can never be a string. Each argument may be any numeric type (including complex).

If imag is omitted, it defaults to zero. If both arguments are omitted, the function returns 0 j. When converting from a string, the string must not contain whitespace around the central + or – operator. For example, complex ( ‘ 1 + 2 j ‘ ) is fine, but complex (‘1 + 2 j ‘ ) raises ValueError.

>>> complex ( )
Oj
>>> complex ( 2 . 51 )
( 2 . 51+0 j )
>>> complex ( 2 . 51 , 4 . 79 )
( 2 . 51+4 . 79 j )
>>> c1=4+5 j 
>>> c2=6+7 j
>>> complex(c1,c2)                                    # Equals ( 4+5 j ) + ( 6+7 j ) j = 4+5 j+6 j - 7 
( -3+11 j )
>>> c= ' 7 '
>>> complex (c)
( 7+0 j )
>>> c=' 7 + 4 j '
>>> complex (c)
( 7+4 j )
>>> x=2+3 j 
>>> x . real
2 . 0
>>> x . imag
3 . 0

delattr ( object , name )
This is a relative of setattr ( ). The arguments are an object and a string. The string must be the name of one of the object’s attributes. The function deletes the named attribute, provided the object allows it.

>>> class new__cls:
. . .                   def ______init_______ ( self , x ) :
. . .                   self. x=x
. . . 
>>> tt=new__cls ( 10 )
>>> tt . x
10 
>>> setattr ( tt ,' x ' , 20 )
>>> tt . x 
20
>>> setattr ( tt, ' y ' ' hello ' )
>>> tt.y 
' hello '
>>> delattr ( tt , ' x ' ) 
>>> tt . x 
Traceback ( most recent call last ) :
File "<stdin>", line 1 , in <module>
AttributeError: new__cls instance has no attribute ’ x ’

divmod ( a , b )
Take two (non-complex) numbers as arguments and return a pair of numbers consisting of their quotient and remainder.

>>> divmod ( 13 . 5 , 3 )
( 4 . 0 , 1 . 5 )
>>> divmod ( 13 , 3 )
( 4 , 1 )

enumerate ( sequence , start=0 )
Return an enumerate object. The sequence argument must be a sequence, an iterator, or some other object which supports iteration, while start is a count (default argument as 0).

>>> seasons=[ ' Spring ' , ' Summer ' , ' Fall ' , ' Winter ' ]
>>> list (enumerate ( seasons ) )
[ ( 0 ,' Spring ' ) , ( 1 , ' Summer ' ) , ( 2 , ' Fall ' ) , ( 3 , ' Winter ' ) ]
>>> list (enumerate ( seasons , start=2 ) )
[ ( 2 ,' Spring ' ) , ( 3 , ' Summer ' ) , ( 4 , ' Fall ' ) , ( 5 , ' Winter ' ) ] 
>>> for num , seasn in enumerate ( seasons , start=1 ) :
. . . print "[{0}] {1 } " . format ( num , seasn )
. . . 
[1] Spring
[2] Summer
[3] Fall
[4] Winter

filter ( function , iterable )
Create a list from those elements of iterable for which function returns True. The iterable may be either a sequence, a container that supports iteration, or an iterator. If iterable is a string or a tuple, the result also has that type, otherwise, it will be a list. If function is None, the identity function is assumed, that is, all elements of iterable that are false are removed.

>>> def isOdd ( x ) :
. . .               if ( x % 2 )==1: return True
. . .               else : return False
>>> filter ( isOdd, [88 , 43 , 65 ,-11 ,202 ] )
[ 43, 65, -11 ]
>>>
>>> def isLetter ( c ) : return c . isalpha ( )
. . . 
>>> filter ( isLetter,"01234abcdeFGHIJ* ( &!∧")
' abcdeFGHIJ '
>>> list= [ 0, 1, ( ) , (2, ) , 0 . 0, 0 . 25 ]
>>> filter ( None , list )
[1 , (2 ,), 0 . 25 ]
>>> filter ( boo1 , list )
[ 1 , ( 2 , ) , 0 . 25 ]

getattr ( object , name [ , default ] )
Return the value of the named attribute of the object; the name must be a string. If the string is the name of one of the object’s attributes, the result is the value of that attribute. If the named attribute does not exist, default is returned if provided, otherwise, AttributeError is raised. For example, a complex number object has real and imag attributes.

>>> a=3 . 5 + 4 . 9 J 
>>> type ( a ) 
<type ' complex '>
>>> getattr ( a , ' real ' )
3 . 5
>>> getattr (a , ' imag ' )
4 . 9
>>> getattr ( a ,' imagine ' , 2 . 2 )
2 . 2

globals ( )
Return a dictionary representing the current global symbol table. The following script “GlobalScope.py” gives some idea about the use of this function.

# Filemame: GlobalScope . py 
var1=10 
def func (  ): 
var2=20 
func ( )
if ' var1 ' in globals ( ) . keys ( ) :
            print "'var1' is a global variable of this module" 
if 'var2' in globals ( ) . keys ( ) :
            print "'var2' is a global variable of this module"

The output is:

’ var1 ' is a global variable of this module

hasattr ( object , name )
The arguments are an object and a string. The result is True, if the string is the name of one of the object’s attributes, otherwise False.

>>> a=3.5+4.9 J
>>> hasattr( a , ' imag ' ) 
True 
>>> hasattr ( a,' imagine ' ) 
False

hash ( )
In computing, a hash table (also “hash map”) is a data structure that can map keys to values. A hash table uses a hash function to compute an index (or hash value) into an array of buckets or slots, from which the correct value can be found. The built-in function hash ( ) return the hash value of the object (if it has one) which is basically an integer and it never changes during its lifetime.

Hashability makes an object usable as a dictionary key and a set member because these data structures use the hash value internally. All of Python’s immutable built-in objects are hashable, while no mutable containers (such as lists or dictionaries) are hashable.

>>> d= { ' Lisa ' : 88 . 5 , ' John ' : 69 . 73 , ' Mike ' : 88 . 5 }
>>> hash ( d [ ' Lisa 1 ' ] )
1485012992
>>> hash ( d [ ' John ' ] )
-1664573625
>>> hash ( d [ ' Mike ' ] )
1485012992

Python Handwritten Notes Chapter 3 img 1

Consider the following example :

>>> map ( hash , ( " namea " , " nameb " , " namec " , " named " ) )
[-1658398457 , -1658398460 , -1658398459 , -1658398462 ]
>>> map ( hash , ( 0 , 1 , 2 , 3 ) )
[ 0 , 1 , 2 , 3 ]

It can be observed that the strings are quite close in their letters, and their hashes are close in terms of numerical distance which is desirable behavior. If the keys are close in nature, one wants their hashes to be close as well so that lookups remain fast. Integers have the same hash value as themselves.

help ( [ object ] )
This function invokes the built-in help system (this function is intended for interactive use). If no argument is given, the interactive help system starts on the interpreter console. If the argument is a string, then the string is looked up as the name of a module, function, class, method, keyword, or documentation topic, and a help page is printed on the console. If the argument is any other kind of object, a help page on the object is generated.

>>> help (cmp)
Help on built-in function cmp in module ____builtin____ :
cmp ( . . . )
    cmp ( x , y ) -> integer

      Return negative if x<y , zero if x==y , positive if x>y .

hex ( x )
Convert an integer number (of any size) to a hexadecimal string. To obtain a hexadecimal string representation for a float, use the float. hex ( ) method.

>>> hex ( 25 )
' 0x19 '

id ( object )
Return the identity of the object. This is an integer (or long integer) which is guaranteed to be unique and constant for this object during its lifetime. Two objects with non-overlapping lifetimes may have the same id ( ) value.

>>> a=5 
>>> id ( a )
3885104 
>>> b= ' hello '
>>> id ( b )
44148000

input ( [ prompt ] )
This function is used to take input from user and evaluates the expression. There is also raw_input ( ) function which takes input from user, convert it to a string, and returns that.

>>> aa=4 
>>> bb=6
>>> resultl=input( ' ----> ' )
- - - >aa+bb 
>>> result2=raw__input ( ' ---> ' )
----->aa+bb
>>>
>>> result1
10
>>> result2
' aa+bb ' 

isinstance ( object , classinfo )
Return True, if the object argument is an instance of the classinfo argument, or of a subclass thereof.

>>> class new__cls :
. . .        def _____init______ ( self , x ) : 
. . .              self . x=x 
. . . 
>>> tt=new_cls ( 10 )
>>> isinstance ( tt , new_cls )
True

Also return True, if classinfo is a type object, and an object is an object of that type or of a subclass thereof. If the object is not a class instance or an object of the given type, the function always returns False.

>>> i=5 
>>> type ( i )
<type ' int '>
>>> type ( int ) 
<type ' type ' >
>>> isinstance ( i , int )
True
>>> isinstance ( i , str )
False

If classinfo is neither a class object nor a type object, it may be a tuple of class or type objects (other sequence types are not accepted). If classinfo is not a class, type, or tuple of classes, types, a TypeError exception is raised.

>>> isinstance( i ,( str , int , float , complex ) )
True

issubcTass ( class , classinfo )
Return True, if class is a subclass of classinfo.

>>> class A: 
. . .        pass
. . . 
class B(A):
. . .        pass
. . . 
>>> class C: 
. . .         pass
. . . 
>>> class D:
. . .        pass
. . . 
>>> issubclass ( B, A )
True

A class is considered a subclass of itself.

>>> issubclass ( D , D )
True

The classinfo may be a tuple of class objects, in which case every entry in classinfo will be checked. In any other case, a TypeError exception is raised.

>>> issubclass ( B , ( A , C , D ) )
True

len ( s )
Return the length (the number of items) of an object s. The argument may be a sequence (string, tuple or list) or a mapping (dictionary).

>>> len ( ' abed ' )
4
>>> seq=[ ' a ' , ' b ' , ' c ' , ' d ' ]
>>> len ( seq )
4
>>> seq= ( ' a ' , 'b \ 'c \ 'd')
>>> len ( seq )
4
>>> dict= { ' a ' : 8 , ' b ' :  9 , ' c ' : 10 , ' d ' : 11 }
>>> len ( diet )
4 '
>>> len ( ' ' )
0

locals ( )
The function returns a dictionary representing the current local symbol table.

# ! / usr / bin / env python 
# Filemame: LocalScope . py 
var1=10
var2=20 
    def func ( ) :
      var3=30 
       var4=40
print ' Local variables of func ( ) = ',locals ( ) 
func ( )
if 'var1' in locals ( ).keys ( ) and 'var2' in locals ( ) . keys( ) :
    print "'var1': and ' var2 ' are local variables of this module"

Output is:

Local variables of func( )= { ' var4 ' : 40 , ' var3 ' : 30 }
' var1 ' and ' var2 ' are local variables of this module

map ( function,iterable, . . . )
Apply function to every item of iterable and return a list of the results. If additional iterable arguments are passed, the function must take that many arguments and is applied to the items from all iterables in parallel. If one iterable is shorter than another, it is assumed to be extended with None items.

If the function is None, the identity function is assumed; if there are multiple arguments, map ( ) returns a list consisting of tuples containing the corresponding items from all iterables. The iterable arguments may be a sequence or any iterable object; the result is always a list.

>>> def add100 ( x ) :
. . .        return x+100
. . .
>>> map ( add100 , ( 44 , 22 , 66 ) )
[ 144 , 122 , 166 ]
>>>
>>> def abc ( a , b , c ) :
. . .        return a*10000+b*100+c
. . . 
>>> map ( abc , ( 1 , 2 , 3 ) , ( 4 , 5 , 6 ) , ( 7 , 8 , 9 ) )
[ 10407 , 20508 , 30609 ]
>>>
>>> map ( None , range ( 3 ) )
[ 0 , 1 , 2 ]
>>> map (None,range ( 3 ) , ' abc ' , [ 44 , 55 , 66 ] )
[ ( 0 , ' a ' , 44 ) , ( 1, -b ’ , 55 ) , ( 2 , *c ', 66 ) ]

max ( iterable [ , key ] )
Return the largest item in an iterable. The optional argument key specifies a function of one argument that is used to extract a comparison key from each list element. The default value is None (compare the elements directly),

>>> max ( ' hello ' )
' o '
>>> max ( [10, 80, 90, 20,-100] )
90 
>>> def LessThanFifty ( x ) :
. . .         if x<=50 :
. . .          return x
>>> max ( [ 10 , 80 , 90 , 20 , -100 ] , key=LessThanFifty )
20

The function has another form max (arg1, arg2, *args [, key] ), which returns the largest of two or more arguments.

>>> max ( ' hi ' ,  ' hello ' ,  ' bye ' ) 
' hi '
>>> max ( ' Gumby ' , ' Lambert ' , ' Sartre ' , ' Cheddar ' )
' Cheddar '
>>> max ( ' Gumby ' , ' Lambert ' , ' Sartre ' , ' Cheddar ' , key=str.upper )
' Sartre '

min ( iterable [ , key ] )
Return the smallest item in an iterable. The key has same meaning as that in max ( ) function.

>>> min ( ' hello' )
' e '
>>> min ( ( 10 , 80 , 90 , 20 , -100 } )
-100

The function has another form min (arg1, arg2, *args [ , key] ), which returns the smallest of two or more arguments.

>>> min ( 10 , 80 , 90 , 20 , -100 )
-100
>>> def rev ( x ) : return -x
. . . 
>>> min ( 10 , 80 , 90 , 20 , -100 , key=rev )
90

next ( iterator [ , defauIt ] )
Retrieve the next item from the iterator. If the default is given, it is returned if the iterator is exhausted, otherwise, Stoplteration is raised.

>>> it=iter ( xrange ( 0 , 3 ) )
>>> next ( it , ' Done ' )
0
>>> next ( it , ' Done ' )
1
>>> next ( it ,  'Done ' ) 
2 
>>> next ( it , ' Done ' ) 
' Done '
>>> next ( it , ' Done ' )
' Done ' 
>>> it=iter ( xrange ( 0 , 3 ) )
>>> next ( it )
0
>>> next ( it )
1 
>>> next ( it )
2
>>> next ( it ) 
Traceback ( most recent call last ) :
File "<stdin>", line 1, in <module>
Stoplteration

oct ( x )
Convert an integer number (of any size) to an octal string.

>>> oct ( 135 )
' 0207 '

pow ( x , y [ , z ] )
Return x to the power y; if z is present, return x to the power y, and modulo z (computed more efficiently than pow (x, y) %z). The two-argument form pow (x, y) is equivalent to using the power operator x* *y. The arguments must be of numeric types. If the second argument is negative, the third argument must be omitted. If z is present, x and y must be of integer types, and y must be non-negative.

>>> 2 * * 4 
16
>>> pow ( 2 , 4 )
16
>>> ( 2 * * 4 ) % 3 
1
>>> pow ( 2 , 4 ,3 )
1

print ( * objects , sep=’ ‘ , end=’ \ n ‘ , file=sys . stdout )
Print objects to the stream file, separated by sep and followed by end. If sep, end and file, are present, they must be given as keyword arguments. All non-keyword arguments are converted to strings and written to the stream, separated by sep and followed by end. Both sep and end must be strings, they can also be None, which means to use the default values. If no objects are given, print ( ) will just write end. The file argument must be an object with a write ( ) method, if it is not present or None, sys. stdout (file objects corresponding to the interpreter’s standard output stream) will be used.

This function is not normally available as a built-in function, since the name print is recognized as the print statement. To disable the statement and use the print ( ) function, use the following future statement before using the function.

>>> from _____future______ import print_function
>>> x , y=3 , 5
>>> print ( ' The sum of ' , x , ' plus ' , y , ' is ' , x+y )
The sum of 3 plus 5 is 8
>>> print ( ' The sum of ' , x , ' plus ' , y , ' is ' , x+y , sep =' ' )
The sum of 3 plus 5 is 8
>>> print ( ' The sum of ' , x , ' plus ' , y , ' is ' , x+y , sep='  ' , end=' \ n The \ n End \ n ' )
The sum of 3 plus 5 is 8
The 
End

range( start,stop[,step] )
This function creates list whose elements are in arithmetic progression. The arguments must be plain integers. If the step argument is omitted, it defaults to 1. If the start argument is omitted, it defaults to 0. step must not be zero (or else ValueError is raised).

>>> range ( 10 )
[ 0 , 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 ]
>>> range ( 1 , 11 ) 
[ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 ]
>>> range ( 0 , 30 , 5 ) 
[ 0 , 5 , 10 , 15 , 20 , 25 ]
>>> range ( 0 , 10 , 3 ) 
[ 0 , 3 , 6 , 9 ] 
>>> range ( 0 , -10 , -1 ) 
[ 0 , -1 , -2 , -3 , -4 , -5 , -6 , -7 , -8 , -9 , ]
>>> range ( 0 )
[ ]
>>> range ( 10 , 5 )
[ ]
>>> range ( 10 , 5 , -1 )
[ 10 , 9 , 8 , 7 , 6 ]

reload ( module )
Reload a previously imported module. The argument must be a module object, so it must have been successfully imported before. This is useful if the programmer has edited the module’s source file using an external editor and wants to try out the new version without leaving the Python interpreter. The return value is the module object.

reversed ( seq )
The function returns an iterator object that can iterate over all the objects in the container in reverse order.

>>> Seq= [ 10, 20, 30 ]
>>> revSeq=reversed ( Seq ) 
>>> for item in revSeq: print item
. . . 
30 
20
10

round ( number [ , ndigits ] )
Return the floating-point value number rounded to digits after the decimal point. If digits are omitted, it defaults to zero.

>>> round ( 2 .769753 )
3 . 0
>>> round ( -2 . 769753 )
-3 . 0 
>>> round ( 2 . 769753 , 4 )
2 . 7698
>>> round ( -2 . 769753 , 4 )
-2 . 7698

setattr ( object, name, value )
This is the counterpart of getattr ( ). The arguments are an object, a string, and an arbitrary value. The string may name an existing attribute or a new attribute. The function assigns the value to the attribute, provided the object allows it. The following example will become clearer after going through chapter 6.

>>> class new_cls:
. . .             def init ( self , x ) :
. . .           self . x=x
>>> tt=new_cls ( 10 )
>>> tt.x 
10
>>> setattr ( tt , ' x ' , 20 )
>>> tt.x 
20
>>> setattr ( tt , ' yhello ' )
>>> tt.y 
' hello '

slice ( start , stop [ , step ] )
Return a slice object representing the set of indices specified by range (start, stop, step). The function can also be of form slice (stop), where the start and step arguments default to None. Slice objects have read-only data attributes start, stop, and step, which merely returns the argument values (or their default).

>>> slice ( 20 ) 
slice ( None , 20 , None )
>>> s1=slice ( 2 , 20 , 3 ) 
>>> type ( s1 ) 
<type ' slice ' >
>>> s1 . start 
2 
>>> s1 . stop 
20
>>> s1 . step 
3

The slice object can be passed to the ________getitem__________ ( ) method of the built-in sequences.

>>> range ( 50 ). getitem ( s1 )
[ 2 , 5 , 8 , 11 , 14 , 17 ]

Or use slice objects directly in subscripts:

>>> range ( 50 ) [ s1 ]
[ 2 , 5 , 8 , 11 , 14 , 17 ]

sorted ( iterable [ , cmp [ , key [ , reverse] ] ] )
Return a new sorted list from the items in iterable. The arguments cmp, key, and reverse are optional.

>>> a= [ 66 . 25 , 333 , ' abc ' , 333 , 1 , ’ ab ' , 1234 . 5 ]
>>> sorted ( a )
[ 1 , 66 . 25 , 333 , 333 , 1234 . 5 , ' ab ' , ' abc ' ]
>>> sorted ( { 10 : ' D ' , 5 : ' B ' , 8 : ' B ' , 6 : ' E ' , 2 : ' A ' } )
[ 2 , 5 , 6 , 8 , 10 ]

cmp specifies a custom comparison function of two arguments (iterable elements) which should return a negative, zero or positive number depending on whether the first argument is considered smaller than, equal to, or larger than the second argument. The default value is None.

key specifies a function of one argument that is used to extract a comparison key from each list element. The default value is None (compare the elements directly).

>>> strs= [ ' ccc ' , ' aaaa ' , ' d ' , ' bb ' ]
>>> sorted ( strs , key=len)                               # Sorted by string length
[ ' d ' , ' bb ' , ' ccc ' , 'aaaa ' ]
>>> student_tuples=[
. . . ( ' john ' , ' A ' , 15 ) ,
. . . ( ' jane ' , ' B ' , 12 ) ,
. . . ( ' dave ' , ' B ' , 10 ) , ]
>>> sorted ( student_tuples , key=lambda student : student [ 2 ] )                        # By age 
[ ( ' dave ' , ' B ' , 10 ) , ( ' jane ' , ' B ' , 12 ) , ( ' john ' , ' A ' , 15 ) ]

the reverse is a boolean value. If set to True, then the list elements are sorted as if each comparison were reversed.

>>> a= [ 66 . 25 , 333 , ' abc ' , 333 , 1 , ' ab ' , 1234 . 5 ]
>>> sorted ( a , reverse = True )
[ ' abc ' , ' ab ' , 1234 . 5 , 333 , 333 , 66 . 25 , 1 ]

In general, the key and reverse conversion processes are much faster than specifying an equivalent cmp function. This is because cmp is called multiple times for each list element, while key and reverse touch each element only once.

>>> L= [ ' geas ' , ' clue ' , ' Zoe ' , ' Ann ' ]
>>> sorted ( L )
[ ' Ann ' , ' Zoe ' , ' clue ' , ' geas ' ]
>>> def ignoreCase(x,y) :
. . . return cmp ( x . upper ( ) , y . upper ( ) ) 
. . . 
>>> sorted ( L , ignoreCase )
[ ' Ann ' , ' clue ' , ' geas ' , ' Zoe ' ]
>>> sorted ( L , None , str . upper )
[ ' Ann ' , ’ clue ' , ' geas ' , ’ Zoe ' ]
>>> L
[ ' geas ' , ' clue ' , ' Zoe ' , ' Ann ' ] 

sum ( iterable [ , start ] )
The function returns the sum total of start ( defaults to 0 ) and the items of an iterable.

>>> seq= [ 5 , 7 . 4 , 2 , 11 ]
>>> sum ( seq )
25 . 4
>>> sum ( seq , 10 . 2 )
35 . 6
>>> aa=4
>>> bb=2 . 5
>>> cc=9 . 1
>>> seq= [ aa , bb , cc ]
>>> sum ( seq )
15 . 6

type ( object )
The function returns the type of an object.

>>> i=50 . 7 
>>> type ( i )
<type ' float '>
>>> type ( i ) is float 
True

xrange ( start , stop [ , step ] )
This function is very similar to range ( ), but returns an xrange object instead of a list. This yields the same values as the corresponding list, without actually storing them all simultaneously. The advantage of xrange ( ) over range ( ) is minimal, except when a very large range is used on a memory-starved machine or when all of the range ( ) elements are never used (such as when the loop is usually terminated with break). The function can also be used as xrange (stop).

The xrange type is an immutable sequence that is commonly used for looping. The advantage of the xrange type is that an xrange object will always take the same amount of memory, no matter the size of the range it represents. There are no consistent performance advantages. The xrange objects support indexing, iteration, and the len ( ) function.

>>> for i in xrange ( 2000000000 ) :
. . . print i
. . . if i > 5 :
. . . break 
. . . 
0
1
2
3
4
5
6
>>> for i in range ( 2000000000 ) :
. . . print i
. . . if i>5 :
. . . break
. . .
Traceback ( most recent call last ) :
File "<stdin>", line 1, in <module>
MemoryError

zip ( [ iterable , . . . ] )
This function returns a list of tuples, where the /th tuple contains the /th element from each of the argument sequences or iterables. The returned list is truncated in length to the length of the shortest argument sequence. When there are multiple arguments that are all of the same lengths, zip ( ) is similar to map ( ) with an initial argument of None. With no arguments, it returns an empty list, zip ( ) in conjunction with the * operator can be used to unzip a list:

>>> x= [ 1 , 2 , 3 ]
>>> y=[ 4 , 5 , 6 , 7 , 8 ]
>>> zipped=zip ( x , y )
>>> zipped
[ ( 1 , -4 ) , ( 2 , 5 ) , ( 3 , 6 ) ]
>>> zip ( x )
[ ( 1 , ) , ( 2 , ) , ( 3 , ) ]
>>> x2 , y2=zip ( *zipped )
>>> x2 
( 1 , 2 , 3 )
>>> y2 
( 4 , 5 , 6 )
>>> zip ( ) 
[ ]

Python Programming – Compound statement Built-in functions Read More »

Basics of Python – String Operations

In this Page, We are Providing Basics of Python – String Operations. Students can visit for more Detail and Explanation of Python Handwritten Notes Pdf.

Basics of Python – String Operations

String operations

Some of the string operations supported by Python are discussed below.

Concatenation

Strings can be concatenated using + operator.

>>> word=' Python '+' Program '
>>> word
' Python Program '

Two string literals next to each other are automatically concatenated; this only works with two literals, not with arbitrary string expressions.

>>> ' Python ' ' Program '
' Python Program ' 
>>> word1=' Python '
>>> word2=' Program '
>>> word1 word2
File "<stdin>", line 1
word1 word2
                   ∧
SyntaxError: invalid syntax

Repetition

Strings can be repeated with the * operator.

>>> word=' Help '
>>> word * 3
' Help Help Help '
>>> 3 * word
' Help Help Help '

Membership operation

As discussed previously, membership operators in and not in are used to test for membership in a sequence.

>>> word=' Python '
>>> 'th' in word
True
>>> ' T ' not in word
True

Slicing operation

The string can be indexed, the first character of a string has sub-script (index) as 0. There is no separate character type; a character is simply a string of size one. A sub-string can be specified with the slice notation.

>>> word=' Python'
>>> word [2]
' t '
>>> word [0:2]
' Py '

String slicing can be in form of steps, the operation s [ i : j : k ] slices the string s from i to j with step k.

>>> word [1 :6 : 2]
' yhn '

Slice indices have useful defaults, an omitted first index defaults to zero, an omitted second index defaults to the size of the string being sliced.

>>> word [ : 2]
' Py '
>>> word [2 : ]
' thon '

As mentioned earlier, the string is immutable, however, creating a new string with the combined content is easy and efficient.

>>> word [0] = ' J '
Traceback (most recent call last) :
File "<stdin>", line 1, in <module>
TypeError : 'str' object does not support item assignment
>>> 'J ' + word[ 1 : ]
' Jython '

If the upper bound is greater than the length of the string, then it is replaced by the string size; an upper bound smaller than the lower bound returns an empty string.

>>> word [ 2 : 50 ]
'thon '
>>> word [ 4 : 1 ]
' '

Indices can be negative numbers, which indicates counting from the right-hand side.

>>> word [ -1 ]
' n '
>>> word [ -2 ]
' o '
>>> word [ -3 : ] 
' hon '
>>> word [ : -3 ]
' Pyt ' 
>>> word[-0]     # -0 is same as 0
' P '

Out-of-range negative slice indices are truncated, but a single element (non-slice) index raises the IndexError exception.

>>> word [ -100 : ]
' Python '
>>> word [ -100 ]
Traceback (most recent call last) :
File "<stdin>", line 1, in <module>
IndexError : string index out of range

String formatting

String objects have an interesting built-in operator called modulo operator (%). This is also known as the “string formatting” or “interpolation operator”. Given format%values (where a format is a string object), the % conversion specifications in format are replaced with zero or more elements of values. The % character marks the start of the conversion specifier.

If the format requires a single argument, values may be a single non-tuple object. Otherwise, values must be a tuple with exactly the number of items specified by the format string, or a single mapping object (a dictionary). If the dictionary is provided, then the mapping key is provided in parenthesis.

>>> ' %s Python is a programming language. ' % ' Python '
' Python Python is a programming language. '
>>> ' %s Python is a programming language. ' % ( ' Python ' )
' Python Python is a programming language.'
>>>
>>> ' %s has %d quote types. ' % ( ' Python ' , 2 )
' Python has 2 quote types. '
>>> ' %s has %03d quote types. ' % ( ' Python ' , 2 )
' Python has 002 quote types. '  
>>> ' %( language )s has % ( number ) 03d quote types.' % \
. . . { " language " : " Python " , " number " : 2 }
' Python has 002 quote types. '

In the above example, 03 consists of two components:

  • 0 is a conversion flag i.e. the conversion will be zero-padded for numeric values.
  • 3 is minimum field width (optional).
ConversionMeaning
DSigned integer decimal.
1Signed integer decimal.
EFloating-point exponential format (lowercase).
EFloating-point exponential format (uppercase).
FFloating-point decimal format.
FFloating-point decimal format.
gFloating point format. Uses lowercase exponential format if the exponent is less than -4 or not less than precision, decimal format otherwise.
GFloating point format. Uses uppercase exponential format if the exponent is less than -4 or not less than precision, decimal format otherwise.
sString.

Precision (optional) is given as a dot (.) followed by the precision number. While using conversion type f, F, e, or E, the precision determines the number of digits after the decimal point, and it defaults to 6.

>>> " Today's stock price : %f " % 50
"Today's stock price: 50 000000"
>>> "Today's stock price : %F " % 50
"Today's stock price: 50 000000"
>>>
>>> "Today's stock price : %f " % 50.4625
"Today's stock price : 50 462500"
>>> "Today's stock price : %F " % 50.4625
"Today's stock price : 50 462500"
>>>
>>> "Today's stock price : %f " % 50.46251987624312359
"Today's stock price : 50. 462520"
>>> "Today's stock price : %F " % 50.46251987624312359
"Today's stock price : 50. 462520"
>>>
>>> "Today's stock price : %. 2f " % 50 . 4625
"Today's stock price : 50.46"
>>> "Today's stock price : %. 2F " % 50 . 4625
"Today's stock price : 50.46"
>>>
>>> "Today's stock price : %e " % 50 . 46251987624312359
"Today's stock price : 5 . 046252e+01 "
>>> "Today's stock price : %E " % 50 . 46251987624312359
"Today's stock price : 5 . 046252e+01 "
>>> "Today's stock price : % 3e " % 50 . 46251987624312359
"Today's stock price : 5 . 046e + 01 "
>>> "Today's stock price : % 3E " % 50 . 46251987624312359
"Today's stock price : 5 . 046E + 01 "

While using conversion type g or G, the precision determines the number of significant digits before and after the decimal point, and it defaults to 6.

>>> " Today's stock price : %g" % 50.46251987624312359
"Today's stock price: 50.4625"
>>> "Today's stock price: %G" % 50.46251987624312359
"Today's stock price: 50.4625"
>>>
>>> "Today's stock price: %g" % 0.0000005046251987624312359
"Today's stock price: 5.04625e-07"
»> "Today's stock price: %G" % 0.0000005046251987624312359
"Today's stock price: 5.04625E-07"

Python String Programs

Basics of Python – String Operations Read More »

Basics of Python – Regular Expression Module

In this Page, We are Providing Basics of Python – Regular Expression Module. Students can visit for more Detail and Explanation of Python Handwritten Notes Pdf.

Basics of Python – Regular Expression Module

Regular expression module

A regular expression (also called RE, or regex, or regex pattern) is a specialized approach in Python, using which programmers can specify rules for the set of possible strings that need to be matched; this set might contain English sentences, e-mail addresses, or anything. REs can also be used to modify a string or to split it apart in various ways.

Meta characters

Most letters and characters will simply match themselves. For example, the regular expression test will match the string test exactly. There are exceptions to this rule; some characters are special “meta characters”, and do not match themselves. Instead, they signal that some out-of-the-ordinary thing should be matched, or they affect other portions of the RE by repeating them or changing their meaning. Some of the meta characters are discussed below:

Meta character

Description

Example

[ ]

Used to match a set of characters.

[time]

The regular expression would match any of the characters t, i, m, or e.

[a-z]

The regular expression would match only lowercase characters.

Used to complement a set of characters.[time]

The regular expression would match any other characters than t, i, m or e.

$

Used to match the end of string only.time$

The regular expression would match time in ontime, but will not match time in timetable.

*

Used to specify that the previous character can be matched zero or more times.tim*e

The regular expression would match strings like timme, tie and so on.

+

Used to specify that the previous character can be matched one or more times.tim+e

The regular expression would match strings like timme, timmme, time and so on.

?

Used to specify that the previous character can be matched either once or zero times.tim ?e

The regular expression would only match strings like time or tie.

{ }

The curly brackets accept two integer values. The first value specifies the minimum number of occurrences and the second value specifies the maximum of occurrences.tim{1,4}e

The regular expression would match only strings time, timme, timmme or timmmme.

Regular expression module functions

Some of the methods of re module as discussed below:

re. compile ( pattern )
The function compile a regular expression pattern into a regular expression object, which can be used for matching using its match ( ) and search ( ) methods, discussed below.

>>> import re
>>> p=re.compile ( ' tim*e ' )

re. match ( pattern, string )
If zero or more characters at the beginning of the string match the regular expression pattern, match-( ) return a corresponding match object instance. The function returns None if the string does not match the pattern.

re. group ( )
The function return the string matched by the RE.

>>> m=re .match ( ' tim*e' , ' timme pass time ' )
>>> m. group ( )
' timme '

The above patch of code can also be written as:

>>> p=re. compile ( ' tim*e ' )
>>> m=p.match ( ' timme pass timme ' )
>>> m.group ( )
'timme'

re. search ( pattern, string )
The function scans through string looking for a location where the regular expression pattern produces a match, and returns a corresponding match object instance. The function returns None if no position in the string matches the pattern.

>>> m=re.search( ' tim*e ' ' no passtimmmeee ' )
>>> m.group ( )
' timmme '

The above patch of code can also be written as:

>>> p=re.compile ( ' tim*e ' )
>>> m=p.search ( ' no passtimmmeee ' )
>>> m.group ( )
' timmme '

re.start ( )
The function returns the starting position of the match.

re.end ( )
The function returns the end position of the match.

re.span ( )
The function returns a tuple containing the ( start, end ) indexes of the match.

>>> m=re.search ( ' tim*eno passtimmmeee ' )
>>> m.start ( )
7
>>> m.end ( )
13
>>> m.span ( )
( 7 , 13 )

The above patch of code can also be written as:

>>> p=re.compile ( ' tim*e ' )
>>> m=p.search ( ' no passtimmmeee ' )
>>> m.start ( )
7 
>>> m.end ( )
13
>>> m.span ( )
( 7 , 13 )

re. findall ( pattern, string )
The function returns all non-overlapping matches of pattern in string, as a list of strings. The string is scanned left-to-right, and matches are returned in the order found.

>>> m=re.findall ( ' tim*e ' , ' timeee break no pass timmmeee ' )
>>> m 
[ ' time ' , ' timmme ' ]

The above patch of code can also be written as:

>>> p=re . compile ( ' tim*e ' )
>>> m=p.findall ( ' timeee break no pass timmmeee ' )
>>> m
[ ' time ', ' timmme ' ]

re. finditer ( pattern, string )
The function returns an iterator yielding MatchObject instances over all non-overlapping matches for the RE pattern in a string. The string is scanned left-to-right, and matches are returned in the order found.

>>> m=re.finditer ( ' tim*e ', ' timeee break no pass timmmeee ' )
>>> for match in m :
. . .           print match.group ( )
. . .           print match.span ( )
time 
( 0 , 4 ) 
timmme 
( 21 , 27 )

The above patch of code can also be written as:

>>> p=re.compile( ' tim*e ' )
>>> m=p.finditer ( ' timeee break no pass timmmeee ' )
>>> for match in m :
. . .         print match.group ( )
. . .         print match.span ( )
time 
( 0 , 4 ) 
timmme
( 21 , 27 )

Basics of Python – Regular Expression Module Read More »

Basics of Python – String Methods

In this Page, We are Providing Basics of Python – String Methods. Students can visit for more Detail and Explanation of Python Handwritten Notes Pdf.

Basics of Python – String Methods

String methods

Below are listed some of the string methods which support both strings and Unicode objects. Alternatively, some of these string operations can also be accomplished using functions of the string module.

str.isalnum( )
Return True, if all characters in the string are alphanumeric, otherwise False is returned.

>>> str=" this2009 ”
>>> str.isalnum ( )
True
>>> str=" this is string example. . . .wow ! ! ! "
>>> str.isalnum( )
False

str. isalpha ( )
Return True, if all characters in the string are alphabetic, otherwise False is returned.

>>> str=" this "
>>> str.isalpha ( )
True
>>> str=" this is string example. . . .wow ! ! ! "
>>> str.isalpha ( )
False

str.isdigit( )
Return True, if all characters in the string are digits, otherwise False is returned.

>>> str="this2009" 
>>> str.isdigit ( )
False
>>> str=" 2009 "
>>> str.isdigit ( )
True

str . isspace ( )
Return True, if there are only whitespace characters in the string, otherwise False is returned.

>>> str= "    "
>>> str.isspace ( )
True
>>> str=" This is string example. . . .wow ! ! ! "
>>> str.isspace ( )
False

str.islower ( )
Return True, if all cased characters in the string are in lowercase and there is at least one cased character, false otherwise.

>>> str=" THIS is string example. . . .wow! ! ! "
>>> str.islower( )
False
>>> str=" this is string example. . . .wow ! ! ! "
>>> str.islower ( )
True
>>> str=" this2009 "
>>> str.islower ( )
True
>>> str=" 2009 "
>>> str.islower ( )
False

str.lower ( )
Return a string with all the cased characters converted to lowercase.

>>> str="THIS IS STRING EXAMPLE. . . .WOW ! ! ! "
>>> str.lower ( )
' this is string example. . . .wow ! ! ! '

The above can be imitated using the string module’s function string. lower (s), where s is a string.

>>> import string 
>>> str="THIS IS STRING EXAMPLE. . . .WOW ! ! ! " 
>>> string:lower(str)
' this is String example. . . .wow ! ! ! '

str.isupper ( )
Return True, if all cased characters in the string are uppercase and there is at least one cased character, otherwise False is returned.

>>> str="THIS IS STRING EXAMPLE. . . .WOW ! ! ! "
>>> str.isupper ( )
True
>>> str=" THIS is string example. . . .wow ! ! ! "
>>> str.isupper ( )
False

str.upper ( )
Return a string with all the cased characters converted to uppercase. Note that str . upper () . isupper () might be False, if string contains uncased characters.

>>> str=" this is string example. . . .wow ! ! ! "
>>> str.upper ( )
' THIS IS STRING EXAMPLE. . . . WOW ! ! ! '
>>> str.upper ( ) .isupper ( )
True
>>> str="@1234@"
>>> str.upper ( )
' @1234@ '
>>> str.upper ( ).isupper ( )
False

The above can be imitated using the string module’s function string. upper (s), where s is a string.

>>> str=" this is string example. . . .wow ! ! ! "
>>> string.upper (str)
' THIS IS STRING EXAMPLE. . . .WOW ! ! ! ’
>>> string.upper (str).isupper ( )
True 
>>> str="@1234@"
>>> string.upper(str)
'@1234@' 
>>> string.upper (str).isupper ( )
False

str.capitalize ( )
Return a string with its first character capitalized and the rest lowercase.

>>> str=" this Is stRing example. . . . wow ! ! ! "
>>> str.capitalize ( )
' This is string example. . . .wow ! ! ! '

The above can be imitated using the string module’s function string, capitalize (word), where the word is a string.

>>> str=" this Is stRing example. . . .wow ! ! ! "
>>> string.capitalize ( str )
' This is string example. . . .wow ! ! ! '

str.istitle ( )
Return True, if the string is title cased, otherwise False is returned.

>>> str=" This Is String Example. . .Wow ! ! ! "
>>> str . istitle ( )
True
>>> str=" This is string example. . . .wow ! ! ! "
>>> str.istitle ( )
False

str.title ( )
Return a title cased version of the string, where words start with an uppercase character and the remaining characters are lowercase. It will return unexpected results in cases where words have apostrophes etc.

>>> str=" this is string example. . . .wow ! ! ! "
>>> str.title ( )
' This Is String Example. . . .wow ! ! ! '
>>> str=" this isn't a float example. . . .wow ! ! ! "
>>> str.title ( )
" This Isn'T A Float Example. . . .Wow ! ! ! "

str.swapcase ( )
Return a copy of the string with reversed character case.

>>> str='' This is string example. . . .WOW ! ! ! "
>>> str . swapcase ( ) 
' tHIS IS STRING EXAMPLE. . . .wow ! ! ! '

The above can be imitated using the string module’s function string. swap case (s), where s is a string.

>>> str=" This is string example. . . .WOW ! ! ! "
>>> string, swapcase (str) 
' tHIS IS STRING EXAMPLE. . . .wow ! ! ! '

str.count(sub[,start[, end]])
Return the number of non-overlapping occurrences of sub-string sub in the range [start, end]. Optional arguments start and end are interpreted as in slice notation.

>>> str=" this is string example. . . .wow ! ! ! "
>>> sub=" i "
>>> str.count (sub , 4 , 40)
2
>>> sub=" wow "
>>> str.count(sub)
1

The above can be imitated using string module’s function string. count (s, sub [, start [, end] ] ), where s is a string.

>>> str=" this is string example. . . .wow ! ! ! "
>>> sub=" i "
>>> string.count( str , sub , 4 ,40 )
2
>>> sub=" wow "
>>> string.count( str,sub )
1

str.find(sub[,start[,end]])
Return the lowest index in the string where the sub-string sub is found, such that sub is contained in the slice s [ start: end]. Optional arguments start and end are interpreted as in slice notation. Return -1, if the sub is not found.

>>> str1=" this is string example. . . .wow ! ! ! "
>>> str2=" exam "
>>> str1.find ( str2 )
15
>>> str1.find ( str2 , 10 )
15 
>>> str1.find ( str2 , 40 )
-1

The above can be imitated using the string module’s function string. find (s, sub [, start [, end] ]), where s is a string.

>>> str1=" this is string example. . . .wow ! ! ! "
>>> str2=" exam " 
>>> string.find ( str1 , str2 )
15 
>>> string.find(str1 , str2 , 10 )
15
>>> string.find( str1 , str2 , 40)
-1

The find ( ) method should be used only if there is a requirement to know the position of the sub. To check if the sub is a sub-string or not, use the in operator:

>>> ' Py ' in ' Python '
True

str.rfind(sub[,start[, end]] )
Return the highest index in the string where the sub-string sub is found, such that sub is contained within s [start: end]. Optional arguments start and end are interpreted as in slice notation. Return -1 on failure.

>>> str1=" this is really a string example. . . .wow ! ! ! "
>>> str2=" is "
>>> strl.rfind ( str2 )
5
>>> str1.rfind ( str2 , 0 , 10 )
5
>>> strl.rfind ( str2 , 10 , 20 )
-1

The above can be imitated using the string module’s function string.rfind(s, sub [, start [, end] ] ), where s is a string.

>>> str1=" this is really a string example. . . .wow ! ! ! " 
>>> str2=" is "
>>> string.rfind ( str1 , str2 )
5
>>> string.rfind ( str1 , str2 , 0 , 10 )
5
>>> string.rfind ( str1 , str2 , 10 , 0 )
-1

str.index ( sub [ , start [ , end ] ] )
Like find ( ), but raise ValueError when the sub-string is not found.

>>> str1=" this is string example. . . .wow ! ! ! "
>>> str2=" exam "
>.> str1. index ( str2 ) 
15 
>>> str1.index ( str2 , 10 )
15 
>>> str1.index ( str2 , 40 )
Traceback ( most recent call last ) :
File "<pyshell#38>", line 1, in <module>
str1 . index ( str2 , 40 ) 
ValueError: substring not found

The above can’ be imitated using string module’s function string, index (s, sub [, start [, end] ] ), where s is a string.

>>> str1 = " this is string example. . . .wow ! ! ! " 
>>> str2=" exam "
>>> string.index ( str1 , str2 )
15
>>> string. index ( str1 , str2 ,10 )
15
>>> string, index ( str1 , str2 , 40 )
Traceback ( most recent call last ) :
File " <stdin> ", line 1, in <module>
File " C : \ Python27 \ lib \ string.py ", line 328, in index 
return s . index ( *args )
ValueError: substring not found

str.rindex ( sub [ , start [ , end ] ] )
Like rfind ( ), but raises ValueError when the sub-string sub is not found.

>>> str1="this is string example. . . .wow ! ! ! "
>>> str2=" is "
>>> strl.rindex ( str1 , str2 )
5
>>> str1.rindex ( str2 , 10 , 20 )
Traceback (most recent call last) : 
File " <stdin> ", line 1, in <module>
ValueError: substring not found

The above can be imitated using the string module’s function string. rfind ( s, sub [, start [, end] ] ), where s is a string.

>>> str1= " this is string example. . . .wow ! ! ! "
>>> str2=" is "
>>> string.rindex ( str1 , str2 )
5
>>> string.rindex ( str1 , str2 , 10 , 20)
Traceback (most recent call last) :
File "<stdin>", line 1, in <module>
File." C : \ Python27 \ lib \ string.py" , line 337, in rindex 
return s.rindex ( *args )
ValueError: substring not found

str.startswith (prefix [ , start [ , end ] ] )
Return True, if string starts with the prefix, otherwise return False. The prefix can also be a tuple of prefixes to look for. With optional start, test string beginning at that position. With an optional end, stop comparing string at that position.

>>> str=" this is string example. . . .wow ! ! ! "
>>> str.startswith( ' this ' )
True
>>> str.startswith( ' is ' , 2)
True
>>> str.startswith( ' this ' , 10 , 17 )
False
>>> pfx=( ' the ' , ' where ' , ' thi ' )
>>> str. startswith ( pfx )
True

str.endswith ( suffix [ , start [ , end ] ] )
Return True, if the string ends with the specified suffix, otherwise return False. The suffix can also be a tuple of suffixes to look for. The “est starts from the index mentioned by optional argument start. The comparison is stopped indicated by optional argument end.

>>> str=" this is string example. . . .wow ! ! ! "
>>> suffix=" wow ! ! ! "
>>> str.endswith ( suffix )
True
>>> suffix= ( " tot ! ! ! ", " wow ! ! ! " )
>>> str.endswith ( suffix )
True
>>> str.endswith ( suffix,20 )
True
>>> suffix= " is "
>>> str.endswith( suffix , 2 , 4 )
True
>>> str.endswith( suffix , 2 , 6 )
False
>>> str.endswith ( (' hey ’,' bye ',' w ! ! ! ' ) )
True

str. join ( iterable )
Return a string which is the concatenation of the strings in the iterable. The separator between elements is the string str providing this method.

>>> str="-" 
>>> seq= ( " a " , " b " , " c " )
>>> str. join ( seq )
' a-b-c '
>>> seq=[ " a " , " b " , " c " ]
>>> str.join (seq) 
' a-b-c '

The above can be imitated using the string module’s function string, join (words [, sep] ), where words is a list or tuple of strings, while the default value for sep is a single space character.

>>> str="-"
>>> seq= ( "a", "b", "c")
>>> string. join (seq, str)
'a-b-c'
>>> seq= [ ”a”, "b”, "c" ]
>>> string.join(seq,str) 
' a-b-c ’

str.replace ( old , new [ , count ] )
Return a string with all occurrences of substring old replaced by new. If the optional argument count is given, only the first count occurrences are replaced.

>>> str=" this is string example. . . . wow ! ! ! this is really string"
>>> str.replace (" is "," was ")
'thwas was string example. . . .wow ! ! ! thwas was really string’
>>> str=" this is string example. . . .wow ! ! ! this is really string "
>>> str.replace (" is "," was ", 3)
'thwas was string example. . . .wow ! ! ! thwas is really string '

The above can be imitated using the string module’s function string. replace (s, old, new [, max replace ] ), where s is a string and may replace is the same as count (discussed above).

>>> str=" this is string example. . . .wow ! ! ! this is really string"
>>> string.replace (str, " is "," was " )
'thwas was string example. . . .wow ! ! ! thwas was really string'
>>> str=" this is string example. . . .wow ! ! ! this is really string"
>>> string.replace (str," is "," was ", 3)
'thwas was string example. . . .wow ! ! ! thwas is really string'

str.center ( width [ , fillchar ] )
Return centered string of length width. Padding is done using optional argument fillchar (default is a space).

>>> str=" this is string example. . . .wow ! ! ! "
>>> str.center ( 40 ,' a ' )
' aaaathis is string example. . . .wow ! ! ! aaaa'
>>> str="this is string example. . . .wow ! ! ! "
>>> str.center (40)
' this is string example. . . .wow ! ! ! '

The above can be imitated using the string module’s function string, center (s, width [, fillchar ] ), where s is a string.

>>> str=" this is string example. . . .wow ! ! ! "
>>> string.center(str, 40 ,’ a ' )
'aaaathis is string example. . . .wow ! ! ! aaaa'
>>> str="this is string example .... wow!!!"
>>> string.center(str,40)
' this is string example. . . .wow ! ! ! '

str.1just ( width [ , fillchar ] )
Return the string left-justified in a string of length width. Padding is done using the optional argument fillchar (default is a space). The original string is returned if the width is less than or equal to len(str).

>>> str="this is string example. . . .wow! ! ! " 
>>> str . 1 just (50, ' 0 ' )
'this is string example. . . .wow ! ! !000000000000000000 '
>>> str=" this is string example. . . .wow ! ! ! "
>>> str.1just (50)
' this is string example. . . .wow ! ! ! '
>>> str="this is string example. . . .wow ! ! ! "
>>> str.1just (10)
' this is string example. . . .wow ! ! ! '

The above can be imitated using string module’s function string. 1 just (s, width [,fill char] ), where s is a string.

>>> str="this is string example. . . .wow ! ! ! "
>>> string.1just ( str , 50, ' 0 ' )
' this is string example. . . .wow ! ! ! 000000000000000000 '
>>> str=" this is string example. . . .wow ! ! ! "
>>> string.1just ( str , 50 )
'this is string example. . . .wow ! ! ! '

str.rjust ( width [ ,fillchar ] )
Return the right-justified string of length width. Padding is done using the optional argument fillchar (default is a space). The original string is returned if the width is less than or equal to len(str).

>>> str="this is string example. . . .wow ! ! ! "
>>> str.rjust ( 50 , ' 0 ' )
'000000000000000000this is string example. . . .wow ! ! ! '
>>> str=" this is string example. . . .wow ! ! ! "
>>> str.rjust ( 10 , ' 0 ' )
' this is string example. . . .wow ! ! ! '

The above can be imitated using the string module’s function string. rjust (s, width [, fillchar] ), where s is a string.

>>> str="this is string example. . . .wow ! ! ! "
>>> string .r just (str, 50, ’ 0 ’ )
' 000000000000000000this is string example. . . .wow ! ! ! '
>>> str="this is string example. . . .wow ! ! ! "
>>> string.rjust (str , 10 , ' 0 ' ) .
' this is string example. . . .wow ! ! ! '

str.zfill ( width )
Return a string of length width, having leading zeros. The original string is returned, if the width is less than or equal to len(str).

>>> str=” this is string example. . . .wow ! ! ! "
>>> str.zfill (40)
'00000000this is string example. . . .wow ! ! ! ' 
>>> str . zf ill ( 45)
' 0000000000000this is string example. . . .wow ! ! ! '

The above can be imitated using the string module’s function string, zfill (s, width), where s is a string.

>>> str=" this is string example. . . .wow ! ! ! "
>>> string . zfill ( str , 40 ) 
'00000000this is string example. . . .wow ! ! ! ’
>>> string . zfill ( str , 45 ) 
' 0000000000000this is string example. . . .wow ! ! ! '

str.strip ( [ chars ] )
Return a string with the leading and trailing characters removed. The chars argument is a string specifying the set of characters to be removed. If omitted or None, the chars argument defaults to removing whitespace.

>>> str=" 0000000this is string example. . . . wow ! ! ! 0000000 "
>>> str.strip ( ' 0 ' )
'this is string example. . . .wow ! ! ! '

The above can be imitated using the string module’s function string. strip (s [, chars ] ), where s is a string.

>>> str=" 0000000this is string example. . . .wow ! ! ! 0000000"
>>> string, strip (str, ’ 0 ’ )
'this is string example. . . .wow ! ! ! '

str.1strip ( [ chars ] )
Return a string with leading characters removed. The chars argument is a string specifying the set of characters to be removed. If omitted or None, the chars argument defaults to removing whitespace.

>>> str=" this is string example. . . .wow ! ! ! "
>>> str.1strip ( ) 
'this is string example. . . .wow ! ! ! '
>>> str="88888888this is string example. . . .wow ! ! ! 8888888 "
>>> str.1strip ( ' 8 ' ) 
'this is string example. . . .wow ! ! ! 8888888 '

The above can be imitated using string module’s function string. lstrip (s [, chars] ), where s is a string.

>>> str="     this is string example. . . .wow ! ! !       "
>>> string.1strip (str)
' this is string example. . . .wow ! ! ! '
>>> str=" 888S8888this is string example. . . .wow ! ! ! 8888888 "
>>> string.1strip ( str , ' 8 ' )
' this is string example. . . .wow ! ! ! 8888888 '

str.rstrip ( [ chars ] )
Return a string with trailing characters removed. The chars argument is a string specifying the set of characters to be removed. If omitted or None, the chars argument defaults to removing whitespace.

>>> str=" this is string example. . . .wow ! ! ! "
>>> str.rstrip ( )
' this is string example. . . .wow ! ! ! '
>>> str="88888888this is string example. . . .wow ! ! ! 8888888 "
>>> str.rstrip (' 8 ')
' 88888888this is string example. . . .wow ! ! ! '

The above can be imitated using string module’s function string.rstrip (s [, chars] ), where s is a string.

>>> str="   this is string example. . . .wow ! ! ! "
>>> string.rstrip ( str )
' this is string example. . . .wow ! ! ! '
>>> str=  "88888888this is string example. . . .wow ! ! ! 8888888 "
>>> string.rstrip ( str,' 8 ' )
' 88888888this is string example. . . .wow ! ! ! '

str.partition(sep)
Split the string at the first occurrence of sep, and return a tuple containing the part before the separator, the separator itself, and the part after the separator.

>>> str="       this is string example. . . .wow ! ! !        "
>>> str.partition (' s ')
('        thi ' ,  ' s ' , ' is string example. . . .wow ! ! !       ' )

str.rpartition (sep)
Split the string at the last occurrence of sep, and return a tuple containing the part before the separator, the separator itself, and the part after the separator.

>>> str="         this is string example. . . .wow! ! !       "
>>> str.rpartition (' s ' )
(' this is ', ' s ', ' tring example. . . .wow ! ! ! ' )

str.split ( [ sep [ , maxsplit ] ] )
Return a list of the words from the string using sep as the delimiter string. If maxsplit is given, at most maxsplit splits are done (thus, the list will have at most maxsplit + 1 elements). If maxsplit is not specified or -1, then all possible splits are made. If sep is not specified or None, any whitespace string is a separator.

>>> str="Line1-abcdef \nLine2-abc \nLine4-abcd"
>>> str . split ( )
['Line1-abcdef', ' Line2-abc ', ' Line4-abcd ' ]
>>> str.split(' ',1)
[' Line1-abcdef ', '\nLine2-abc \nLine4-abcd ' ]

The above can be imitated using string module’s function string, split (s [, sep [, maxsplit ] ] ), where s is a string.

>>> str="Line1-abcdef \nLine2-abc \nLine4-abcd"
>>> string.split (str)
[ ' Line1-abcdef ', ' Line2-abc ', ' Line4-abcd ' ]
>>> string. split ( str,'   ',1 )
[ ' Line1-abcdef ', ' \nLine2-abc \nLine4-abcd ' ]

str.rsplit ( [ sep [ , maxsplit ] ] )
Return a list of the words from the string using sep as the delimiter string. If maxsplit is given, at most maxsplit splits are done, the rightmost ones. If sep is not specified or None, any whitespace string is a separator. Except for splitting from the right, rsplit () behaves like split () which is described in detail below.

>>> str="       this is string example. . . .wow ! ! !       "
>>> str.rsplit ( )
['this', 'is', 'string', 'example. . . .wow ! ! ! ' ]
>>> str.rsplit ( ' s ' )
['       thi ', ' i ', '   ', ' tring example. . . .wow ! ! ! ' ]

The above can be imitated using string module’s function string. rsplit (s [, sep [, maxsplit ] ] ), where s is a string.

>>> str="          this is string example. . . . wow ! ! !        "
>>> string. rsplit ( str )
[ ' this ' ,  ' is ' , ' string ' , ' example. . . .wow ! ! ! ' ]
>>> string. rsplit ( str , ' s ' )
['          thi' ; ' i ', ' ', 'tring example. . . .wow ! ! !                 ' ]

str. splitlines ( [ keepends ] )
Return a list of the lines in the string, breaking at line boundaries. Line breaks are not included in the resulting list unless keeping is given.

>>> str="1ine1-a b c d e f\n1ine2- a b c\ n\n1ine4- a b c d "
>>> str.splitlines ( )
[ ' Line1-a b c d e f',   ' Line2- a b c ' , '   ' , ' Line4- a b c d ' ]
>>> str. splitlines (0)
[ ' Line1-a b c d e f ', ' Line2- a b c ', '    ', ' Line4- a b c d ' ]
>>> str.splitLines ( Fa1se )
[ ' Line1-a b c d e f ' , ' Line2- a b c ', '    ', ' Line4- a b c d ' ]
>>> str.sp1itLines (1)
[ ' Line1-a b c d e f\n ' , ' Line2- a b c\n', '\n', ' Line4- a b c d ' ]
>>> str.splitLines ( True )
[ ' Line1-a b c d e’ f\n', ' Line2- a b c\n', ' Line4- a b c d ' ]

str.translate ( table [ , deletechars ] )
Return a string having all characters occurring in the optional argument delete chars are removed, and the remaining characters have been mapped through the given translation table, which must be a string of length 256.

The maketrans ( ) function (discussed later in this section) from the string module is used to create a translation table. For string objects, set the table argument to None for translations that only delete characters.

>>> str=' this is string example. . . .wow ! ! ! '
>>> tab=string.maketrans ( ' e ' , ' E ' )
>>> str.translate ( tab )
' this is string ExamplE. . . .wow ! ! ! '
>>> str.translate ( tab , ' ir ' )
' ths s stng ExamplE. . . .wow ! ! ! '
>>> str.translate ( None , ' ir ' )
' ths s stng example. . . .wow ! ! ! '

The above can be imitated using string module’s function string. translate (s, table [, deletechars ] ), where s is a string.

>>> str=’ this is string example. . . .wow ! ! ! '
>>> tab=string.maketrans (' e ',' E ')
>>> string.translate ( str , tab )
' this is string ExamplE. . . .wow ! ! ! '
>>> string.translate ( str , tab ,' ir ' )
' ths s stng ExamplE. . . .wow ! ! ! '
>>> string.translate ( str , None ,' ir ' )
' ths s stng example. . . .wow ! ! ! '

The following functions are there in the string module but are not available as string methods.

string.capwords(s[,sep])
Split the argument s into words using str. split (), then capitalize each word using str. capitalize ( ), and join the capitalized words using str. join ( ). If the optional second argument sep is absent or None, runs of whitespace characters are replaced by a single space, and leading and trailing whitespace is removed, otherwise, sep is used to split and join the words.

>>> str=" this is string example. . . .wow ! ! ! ''
>>> string.capwords (str)
' This Is String Example. . . .Wow ! ! ! '
>>> string.capwords (str, '    ' )
' This Is String Example. . . .Wow ! ! !    '
>>> string, capwords ( str,' s ' )
' this is sTring example. . . . wow ! ! ! ' 

string.maketrans ( from , to )
Return a translation table suitable for passing to translate (), that will map each character in from into the character at the same position in to, from and to must have the same length.

>>> str=' this is string example. . . .wow ! ! ! '
>>> tab=string.maketrans ( ' t! ' , ' T. ' )
>>> string.translate ( str , tab )
'This is sTring example. . . .wow. . . '
>>> string.translate ( str , tab ,' ir ' )
' Ths s sTng example. . . .wow. . . '
>>> string.translate ( str , None , ' ir ' )
' ths s stng example. . . .wow ! ! ! '

Python String Programs

Basics of Python – String Methods Read More »

Basics of Python – String Constants

In this Page, We are Providing Basics of Python – String Constants. Students can visit for more Detail and Explanation of Python Handwritten Notes Pdf.

Basics of Python – String Constants

String constants

Some constants defined in the string module are as follows:

string. ascii_lowercase
It returns a string containing the lowercase letters ‘ abcdefghijklmnopqrstuvwxyz ‘.

>>> import string
>>> string . ascii_lowercase
' abcdefghijklmnopqrstuvwxyz '

string. ascii_uppercase
It returns a string containing uppercase letters ‘ ABCDEFGHIJKLMNOPQRSTUVWXYZ ‘.

>>> string . ascii_uppercase 
' ABCDEFGHIJKLMNOPQRSTUVWXYZ '

string. ascii_letters
It returns a string containing the concatenation of the ascii_lowercase and ascii_uppercase constants.

>>> string . ascii_letters
' abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ '

string. digits
It returns the string containing the digits ‘ 0123456789 ‘.

>>> string.digits 
' 0123456789 '

String.hex digits
It returns the string containing hexadecimal characters ‘ 0123456789abcdef ABCDEF ‘.

>>> string.hexdigits 
' 0123456789abcdef ABCDEF ’

string.octdigits
It returns the string containing octal characters ‘ 01234567 ‘.

>>> string.octdigits 
' 01234567 '

string. punctuation
It returns the string of ASCII characters which are considered punctuation characters.

>>> string.punctuation
‘ ! ” # $ % & \ ‘ ( ) * + , – . / : ; <=> ? @ [ \\ ] ∧ _ ‘ { | } ∼ ‘

string. whitespace
It returns the string containing all characters that are considered whitespace like space, tab, vertical tab, etc.

>>> string.whitespace
‘ \ t \ n \ x0b \ x0c \ r ‘

string. printable
It returns the string of characters that are considered printable. This is a combination of digits, letters, punctuation, and whitespace.

>>> string . printable
' 0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ ! " # $ % & \ ' ( ) * + , - . / : ; <=> ? 0 [ \\ ]∧ _ ' { I \ t \ n \ r \ x0b \ x0c  '

Python String Programs

Basics of Python – String Constants Read More »

Introduction to Python – Python Download and Installation

In this Page, We are Providing Introduction to Python – Python Download and Installation. Students can visit for more Detail and Explanation of Python Handwritten Notes Pdf.

Introduction to Python – Python Download and Installation

Python download and installation

There are many different ways to install Python, the best approach depends upon the operating system one is using, what is already installed, and how the person intends to use it. To avoid wading through all the details, the easiest approach is to use one of the pre-packaged Python distributions that provide built-in required libraries. An excellent choice for Windows operating system users is to install using a binary file which can be downloaded from the official Python’s website (http://www.python.org/download/).

One can install IDLE and Spyder in Ubuntu (Linux) operating system by executing the following commands in the terminal (as shown in Figures 1-4).

sudo apt-get install idle-python2.7 spyder

These can be independently installed using separate commands.

sudo apt-get install idle-python2.7 
sudo apt-get install spyder

Python Handwritten Notes Chapter 1 img 4

Introduction to Python – Python Download and Installation Read More »

Introduction to Python – Integrated Development Environment

In this Page, We are Providing Introduction to Python – Integrated Development Environment. Students can visit for more Detail and Explanation of Python Handwritten Notes Pdf.

Introduction to Python – Integrated Development Environment

Introduction to Python – Integrated development environment

An Integrated Development Environment (IDE) is an application that provides comprehensive facilities for software development. An IDE normally consists of a source code editor, compiler and/or interpreter, and a debugger.

Introduction to Python – IDLE

IDLE is an IDE, and it is the basic editor and interpreter environment which ships with the standard distribution of Python. IDLE is the built using “Tkinter” GUI toolkit, and has the following features:

  • Coded in Python, using the Tkinter GUI toolkit.
  • Cross-platform i.e. works on Windows and Unix.
  • Has source code editor with multiple undo, text highlighting, smart indent, call tips, and many other features (shown in figure 1-2).
  • Has Python shell window, also known as “interactive interpreter” (shown in figure 1-1).

Python Handwritten Notes Chapter 1 img 1
Python Handwritten Notes Chapter 1 img 2

Introduction to Python – Spyder

“Spyder” (previously known as “Pydee”) stands for “Scientific PYthon Development EnviRonment” (shown in figure 1-3), and it is a powerful IDE for the Python language with advanced editing, interactive testing, debugging, and introspection features. This IDE also has the support of “IPython” (enhanced interactive Python interpreter) and popular Python libraries such as NumPy, Matplotlib (interactive 2D/-3D plotting), etc. Some of the key features are:

  • Syntax coloring (or highlighting).
  • Typing helpers like automatically inserting closing parentheses etc.
  • Support IPython interpreter.
  • Contains a basic terminal command window.

Spyder runs on all major platforms (Windows, Mac OSX, Linux), and the easiest way to install Spyder in Windows is through Python(x,y) package (visit http://www.pythonxy.com).

Python Handwritten Notes Chapter 1 img 3
The expressions/codes discussed in this book are written and tested in Spyder IDE.

Introduction to Python – Integrated Development Environment Read More »

Introduction to Python – Python, Pythonic, History, Documentation

In this Page, We are Providing Introduction to Python – Python, Pythonic, History, Documentation. Students can visit for more Detail and Explanation of Python Handwritten Notes Pdf.

Introduction to Python – Python, Pythonic, History, Documentation

Python

Python is a high-level general-purpose programming language that is used in a wide variety of application domains. Python has the right combination of performance and features that demystify program writing. Some of the features of Python are listed below:

  • It is simple and easy to learn.
  • Python implementation is under an open-source license that makes it freely usable and distributable, even for commercial use.
  • It works on many platforms such as Windows, Linux, etc.
  • It is an interpreted language.
  • It is an object-oriented language.
  • Embeddable within applications as a scripting interface.
  • Python has a comprehensive set of packages to accomplish various tasks.

Python is an interpreted language, as opposed to a compiled one, though the distinction is blurry because of the presence of the bytecode compiler (beyond the scope of this book). Python source code is compiled into bytecode so that executing the same file is faster the second time (recompilation from source to bytecode can be avoided). Interpreted languages typically have a shorter development/debug cycle than compiled ones, and also their programs generally also run slowly. Please note that Python uses a 7-bit ASCII character set for program text.

The latest stable releases can always be found on Python’s website (http://www.python.org/). There are two recommended production-ready Python versions at this point in time because at the moment there are two branches of stable releases: 2.x and 3.x. Python 3.x may be less useful than 2.x since currently there is more third-party software available for Python 2 than for Python 3. Python 2 code will generally not run unchanged in Python 3. This book focuses on Python version 2.7.6.

Python follows a modular programming approach, which is a software design technique that emphasizes separating the functionality of a program into independent, interchangeable modules, such that each contains everything necessary to execute only one aspect of the desired functionality. Conceptually, modules represent a separation of concerns and improve maintainability by enforcing logical boundaries between components.

More information on the module is provided in chapter 5. Python versions are numbered in the format A.B.C or A.B, where A is the major version number, and it is only incremented for major changes in the language; B is the minor version number, and incremented for relatively lesser changes; C is the micro-level, and it is incremented for bug-fixed release.

Pythonic

“Pythonic” is a bit different idea/approach of the writing program, which is usually not followed in other programming languages. For example, to loop all elements of an iterable using for statement, usually, the following approach is followed:

food= [ 'pizza', 'burger',1 noodles']
for i in range(len(food)):
print(food[i])

A cleaner Pythonic approach is:

food=['pizza','burger','noodles']
for piece in food:
print(piece)

History

Python was created in the early 1990s by Guido van Rossum at Centrum Wiskunde & Informatica (CWI, refer http://www.cwi.nl/) in the Netherlands as a successor of a language called “ABC”. Guido remains Python’s principal author, although it includes many contributions from others. When he began implementing Python, Guido van Rossum was also reading the published scripts from “Monty Python’s Flying Circus”,.a BBC comedy series from the 1970s. Van Rossum thought he needed a name that was short, unique, and slightly mysterious, so he decided to call the language “Python”. In 1995, Guido continued his work on Python at the Corporation for National Research Initiatives (CNRI, visit http://www.cnri.reston.va.us/) in Reston, Virginia, where he released several versions of the software.

In May 2000, Guido and the Python core development team moved to “BeOpen.com” to form the BeOpen PythonLabs team. In October of the same year, the PythonLabs team moved to Digital Creations (now Zope Corporation, visit http://www.zope.com/). In 2001, the Python Software Foundation (PSF, refer http://www.python.org/psf/) was formed, a non-profit organization created specifically to own Python-related intellectual property. Zope Corporation is a sponsoring member of the PSF.

Documentation

Official Python 2.7.6 documentation can be accessed from the website link: http://docs.python.Org/2/. To download an archive containing all the documents for version 2.7.6 of Python in one of the various formats (plain text, PDF, HTML), follow the link: http://docs.python.Org/2/download.html.

Introduction to Python – Python, Pythonic, History, Documentation Read More »

Basics of Python – String

In this Page, We are Providing Basics of Python – String. Students can visit for more Detail and Explanation of Python Handwritten Notes Pdf.

Basics of Python – String

String

Python can manipulate string, which can be expressed in several ways. String literals can be enclosed in matching single quotes (‘) or double quotes (“); e.g. ‘hello’, “hello” etc. They can also be enclosed in matching groups of three single or double quotes (these are generally referred to as triple- quoted strings), e.g. ‘ hello ‘, “hello”. A string is enclosed in double-quotes if the string contains a single quote (and no double quotes), else it is enclosed in single quotes.

>>> "doesnt"
'doesnt'
>>> "doesn't"
"doesn't"
>>> '"Yes," he said.'
' "Yes., " he said. '

The above statements can also be written in some other interesting way using escape sequences.

>>> "doesn\' t" ;
"doesn ' t”
‘>>> '\"Yes,\" he said.' 
' "Yes," he said.'

Escape sequences are character combinations that comprise a backslash (\) followed by some character, that has special meaning, such as newline, backslash itself, or the quote character. They are called escape sequences because the backslash causes an escape from the normal way characters are interpreted by the compiler/interpreter. The print statement produces a more readable output for such input strings. Table 2-12 mentions some of the escape sequences.

Escape sequence

Meaning

\n

Newline.
\t

Horizontal tab.

\v

Vertical tab.

 

Escape sequence

Meaning
W

A backslash (\).

Y

Single quote (‘).
\”

Double quote (“).

String literals may optionally be prefixed with a letter r or R, such string is called raw string, and there is no escaping of character by a backslash.

>>> str=' This is \n a string '
>>> print str 
This is 
a string
>>> str=r' This is \n a string '
>>> print str 
This is \n a string

Specifically, a raw string cannot end in a single backslash.

>>> str=r ' \ '
File "<stdin>", line 1 
str=r ' \ '
            ∧
SyntaxError: EOL while scanning string literal

Triple quotes are used to specify multi-line strings. One can use single quotes and double quotes freely within the triple quotes.

>>> line=" " "This is
. . . a triple
. . . quotes example" " "
>>> line
' This, is\na triple\nquotes example'
>>> print line
This is
a triple 
quotes example

Unicode strings are not discussed in this book, but just for the information that a prefix of ‘ u ‘ or ‘ U’ makes the string a Unicode string.

The string module contains a number of useful constants and functions for string-based operations. Also, for string functions based on regular expressions, refer to re module. Both string and re modules are discussed later in this chapter.

Python String Programs

Basics of Python – String Read More »