Saturday, August 29, 2015

Easy Essential python notes

 a="Cisco Switch"
a.index("i") #find position of character
a.count("i") #finds number of occurance of character "i"
a.find("sco") #returns 2 as result as sco starts at position 2 (starting number is 0)
a.lower() #convert to lowercase
a.upper() #convert to uppercase
a.startswith("C")  # returns True as it starts with "C"
a.endswith("h")  # returns True as it ends at "h"

# Stripping white space
>>> a="  hello worlddd   "
>>> a.strip()
'hello worlddd'
# Stripping specific character
>>> c = "$$$testing to strp dollar sign from start and end of string$$"
>>> c.strip("$")
'testing to strp dollar sign from start and end of string'


The following example shows the usage of split() method.
#!/usr/bin/python

str = "Line1-abcdef \nLine2-abc \nLine4-abcd";
print str.split( )
print str.split(' ', 1 )
When we run above program, it produces following result −
['Line1-abcdef', 'Line2-abc', 'Line4-abcd']
['Line1-abcdef', '\nLine2-abc \nLine4-abcd'] 

#check if string has digits or whitespace

bool(re.search('[\d\s]',"hellowoldsafasdfads"))








# Replacing characters. Here we remove white space from string
>>> b=" Lili bili tili mili "
>>> b.replace(" ","")
'Lilibilitilimili'

# split the string based on delimiter to a list of elements
>>> name="mahakali,bagmati,seti,karnali"
>>> name.split(",")
['mahakali', 'bagmati', 'seti', 'karnali']

#String formatting

>>>"Average age of %s in %s is %d and attendence is %f percentage" % ("students","class",18,87.654)
>>>'Average age of students in class is 18 and attendence is 87.654000 percentage'

another way by assigning all types of data to string
>>> "Average age of %s in %s is %s and attendence is %s percentage" % ("students","class","18","87.654")
'Average age of students in class is 18 and attendence is 87.654 percentage'


>>> x="hello"
>>> y="hi"
>>> x+y
'hellohi'

>>> x*3
'hellohellohello'
>>> x.find("ters")   #returns negative if false
-1

>>> "zzz" in x   #returns false as "hello" doesnt have "zzz" in it
False
>>> "ll" in x   #true  as "hello" have "ll" in it
True
>>> "zzz" not in x  #same thing but testing "not in x"
True

#python utilizing builtin functions
>>> x
'hello'
>>> print(x.upper())
HELLO

#string array manipulation
district="Ktm Nepal"


>>> district[0:5]    #note 5th element of string array "e" is omitted
'Ktm N'

>>> district[2:]   # outputs elements 2nd array element and rest of elements
'm NepaL'


#in reverse order the string "Ktm Nepal" have below element number
-1=L
-2=a
-3=p
-4=e
-5=N
-6=   #whitespace
-7=m
-8=t
-9=K



>>> district[-9]
'K'
>>> district[-5:-2]
'Nep'
>>> district[-3:-4]  # This will not work if you want to do some reverse order thing
''     #output is nothing




If you want to print last 5 character
district[-5:]

#more string slicing examples




>>> name="testdemo"
>>> name[-3:]
'emo'
>>> name[:-3]    # index -1 to -3 are removed and rest are displayed
'testd'


#Reversing order of string

>>> name[::-1]  
'omedtset' 


Actually float(), int(), str() etc are constructors for their respective classes

Here are the docs about the "new" format syntax. An example would be:
"({:d} goals, ${:d})".format(self.goals, self.penalties)
If both goals and penalties are integers (i.e. their default format is ok), it could be shortened to:
"({} goals, ${})".format(self.goals, self.penalties)
And since the parameters are fields of self, there's also a way of doing it using a single argument twice (as @Burhan Khalid noted in the comments):
"({0.goals} goals, ${0.penalties})".format(self)
Explaining:
  • {} means just the next positional argument, with default format;
  • {0} means the argument with index 0, with default format;
  • {:d} is the next positional argument, with decimal integer format;
  • {0:d} is the argument with index 0, with decimal integer format.
There are many others things you can do when selecting an argument (using named arguments instead of positional ones, accessing fields, etc) and many format options as well (padding the number, using thousands separators, showing sign or not, etc). Some other examples:
"({goals} goals, ${penalties})".format(goals=2, penalties=4)
"({goals} goals, ${penalties})".format(**self.__dict__)

"first goal: {0.goal_list[0]}".format(self)
"second goal: {.goal_list[1]}".format(self)

"conversion rate: {:.2f}".format(self.goals / self.shots) # '0.20'
"conversion rate: {:.2%}".format(self.goals / self.shots) # '20.45%'
"conversion rate: {:.0%}".format(self.goals / self.shots) # '20%'

"self: {!s}".format(self) # 'Player: Bob'
"self: {!r}".format(self) # '<__main__.Player instance at 0x00BF7260>'

"games: {:>3}".format(player1.games)  # 'games: 123'
"games: {:>3}".format(player2.games)  # 'games:   4'
"games: {:0>3}".format(player2.games) # 'games: 004'



result=99.99989
>>> round(result)
100


>>> test=99.5683
>>> round(test)
100
>>> round(test,2)
99.57
>>> round(test,4)
99.5683




           LISTS                  
IT IS MUTABLE or changeable objects, can be initialized by square brackets []

>>> list1 = ["www","http","postman",11,22]
>>> list1[2:]

['postman', 11, 22]
    


>>> fruit=["apple","banana","grapes"]
>>> fruit.append("Guava")
>>> print(fruit)
['apple', 'banana', 'grapes', 'Guava']
>>> fruit.insert(0,"urgen")
>>> print(fruit)
['urgen', 'apple', 'banana', 'grapes', 'Guava']
>>> fruit.insert(2,"Orange")
>>> print(fruit)
['urgen', 'apple', 'Orange', 'banana', 'grapes', 'Guava'] 


Set                          
set is data type similar to a list  but contain only unique element (no duplicate)
eg.

>>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
>>> fruit = set(basket)               # create a set without duplicates
>>> fruit
set(['orange', 'pear', 'apple', 'banana'])
 
>>> a = "apple"
>>> a
'apple'
>>> a = set(a)
>>> a
{'p', 'l', 'a', 'e'}    # note that there is no duplicate of character "p"
 
 

Dictionary/Associative Array                          
 defining dictinary: {key1:value1, key2:value2,}
 personinfo=dict (  name="ram",age=11,address="pokhara"  )  #using dict()
Another method:-
 >>>dict1={"name":"hari", "age":22,"address":"baneshwor","email":"hari@example.com"}
note: here the keys(name,age,address,email) act as the index number (key are not sorted and they can be in any order so we may need to manually arrange order of key)


To append new key/value to dictionary:-
>>> dic1['nationality'] = "Espanyol"
>>> dic1
{'email': 'hari@example.com', 'age': 22, 'name': 'hari', 'nationality': 'Espanyol', 'address': 'baneshwor'}




for indexkey in dict1:
    print(indexkey,dict1[indexkey])

email hari@example.com
age 22
name hari
address baneshwor


To printout Assorted keyvalues:

>>> for kindx in sorted(dic.keys()):
    print(kindx,dic[kindx])

address baneshwor
age 22
email hari@example.com
name hari





###### Finding type and id of python object #######



Immutable:

#    numbers: int, float, complex
 #   immutable sequences: str, tuples, bytes, frozensets

Mutable: everything else,

  # mutable sequences: list, byte array
   # set type: sets
   # mapping type: dict
   # classes, class instancesetc.

And a trick is to use id()built-in function. For instance,

Using on integer:

>>> n = 1
>>> id(n)
**704
>>> n += 1
>>> n
2
>>> id(n)
**736

Using on list:

>>> m = [1]
>>> id(m)
**416
>>> m.append(2)
>>> m
[1, 2]
>>> id(m)
**416


 >>> x=9
>>> y=9
>>> id(x)
1921755008
>>> id(y)
1921755008
>>> z=977
>>> id(z)
54610352
>>> x==y            # Check if variables have same value"Double equalsto "="  "
True
>>> x is y            # Check if variables point to same object
True

###### specifying logical value with True and False

>>> a, b = 10, 11
>>> a
10
>>> b
11
>>> a == b
False
>>> a > b
False
>>> a < b
True

####  If and else statement
vim  ifelse.py
def main():
    a,b=10,100
    #or a=10
    #or b=100
    if a < b:
        print('a is less than b')
    else
        print('b is less than a')

 if __name__ == "__main__": main()


NOTE:  what is  if __name__ == "__main__": main() => if the python interpreter is running that module (the source file) as the main program, it sets the special __name__ variable to have a value "__main__". If this file is being imported from another module, __name__ will be set to the module's name. This trick exists in Python so that our Python files can act as either reusable modules, or as standalone programs.

the above "ifelse.py" file can be imported as module eg.
vim test.py
import ifelse
....

def main():
    var="seven"
    if v=="one":
        print("v is one")
    elif v=="two":         #each one of the condition are executed one time only
        print("v is two")
    elif v=="three":
        print("v is three")
    else:
        print("v is something else")

if __name__ == "__main__": main()

 ##########similar method  like switch statement###########
def main():
    numbers = dict (
    one = "first",
    two = "second",
    three = "third",
    four = "fourth"
    )

    test = "twodd"
    print(numbers.get(test,"other value"))    # prints "other value" if provided key doesnt match existing key in dictionary

if __name__ == "__main__": main()




 


No comments:

Post a Comment