Anda di halaman 1dari 20

String Functions

ljust

end=

strip

lstrip

replace

split

upper
index
count
find
startswith
endswith
in
not
%

"""

type
isinstance
str,int,float
list,tuple
Array Functions
list
len

range
min
max
append
del
pop
remove
insert
extend
sort
reverse
sorted
reversed
set
intersection
difference
union
clear
tuples

dictionary
range

Regular Expression Functions

re.search

re.match

re.findall
System Functions
sys.exit

_
__

__a__

__all__

date
General Functions

pip
help

dir
id

File Functions
mode

seek
tell
read
readline
readlines
String Functions

The method ljust() returns the string left justified in a string of length width. Padding is done using the
specified fillchar (default is a space). The original string is returned if width is less than len(s).
The default value of end is \n meaning that after the print statement it will print a new line. So simply stated
end is what you want to be printed after the print statement has been executed

Return a copy of the string with leading and trailing characters removed. If chars is omitted or None,
whitespace characters are removed. If given and not None, chars must be a string; the characters in the
string will be stripped from the both ends of the string this method is called on.

Strips from left hand side.

The method replace() returns a copy of the string in which the occurrences of old have been replaced with
new, optionally restricting the number of replacements to max
The method split() returns a list of all the words in the string, using str as the separator (splits on all
whitespace if left unspecified), optionally limiting the number of splits to num.
conevrt to upper case
To get the index of the letter in the string
To get the occurence of the letter in the string
To get the starting location of the characters in the string
To check the starting character
To check the ending character
To check the presence of letter in a string
To check the not presence of letter in a string
Format operators
Old Style
New Style
To slice and get the part of the text from the string

To declare string in multiple lines

Will give the data type of the variable


isinstance also just like type but this will be more accurate when checking base class objects
To convert data type to str,int,float
To convert data type to list, tuple
Array Functions
List to store data
This function will return the string length if the given argument is string or array length if the given
argument is array
This fumction tells the start, end and step details for looping
To get the min value in the list
To get the max value in the list
To append value in a list
To delete value in a list using index
pop also will be used to delete value in a list using index
To delete value in a list by using the name
To insert value in a particular location in a list
To join two lists
To sort the list in acsending order and assign to the same list
To sort the list in descending order and assign to the same list
To sort the list in acsending order and NOT assign to the same list
To sort the list in descending order and NOT assign to the same list
Set is same as list but with out duplicate values in it
Gives common values between two sets
Gives different values between two sets
To join two sets
To remove data from the set
Tuples are immutable list, the data cannot be changed or removed

we can create tuple of values and tuple and variables, and use this variables to access values

unordred set of key value pairs enclosed in curly braces seperated by commas
it gives values from 0 to the value-1 in the paranthesis

real usuage
Regular Expression Functions

search the string in the whole sentence for the given patterrn, and extarct the matched string in groups.
group(0): Whole string that matches with the whole given pattern.
group(1), group(2)..group(n): It contains the respective matched string with the given pattern.
Note: The groups are starts and ends with parenthesis.

match the string in the beginning of the sentence and returns the address if exist else returns none.

It helps to get a list of all matching patterns.


System Functions
use sys.exit in programs to stop and exit it from the program

Single underscore at the beginning:

One underscore at the start of a method or attribute name makes it private and you cannot access this
method from outside of the class. And if we want to access it should be from another public method.
Two underscores at the beginning:

This causes a lot of confusion. It should not be used to create a private method. It should be used to avoid
your method to be overridden by a subclass or accessed accidentally.

Two underscores at the beginning and at the end:

When we see a method like __this__, don't call it. Because it means it's a method which python calls, not by
you. There is always an operator or native function which calls these magic methods. Sometimes it's just a
hook python calls in specific situations. For example __init__() is called when the object is created after
__new__() is called to build the instance

when __all__ is used. It is a list of strings defining what symbols in a module will be exported when from
<module> import * is used on the module.
Note: In the given example If the __all__ above is commented out, this code will then execute to
completion, as the default behaviour of import * is to import all symbols that do not begin with an
underscore, from the given namespace.

from time import gmtime, strftime


strftime("%Y-%m-%d %H:%M:%S", gmtime())
General Functions

To install python packages


In python prompt, help will give the details of the module

In python prompt, dir will give the details of the functions in the module
To get the system address where variable stores

File Functions
Read(r), Write(w), Append(a)
When file opens in read mode, the file read happens and cursor reaches the file end and to bring the cursor
back to required position we use seek.
To get the current cursor position
To read the number of characters from the file
To read a line
To read multiple lines
tions

hst[i].ljust(25) "-0: saccblr701 " = 25 characters

print ("hello",end=" +") hello +

answer = " test "


answer=answer.strip(' ') test
todo_id =
TODOS = { int(max(TODOS.keys()).lstrip('todo')) +
'todo1': {'task': 'build an API'}, 1
'todo2': {'task': 'profit!'},}

answer=answer.replace("test", "extend")
answer=answer.split(' ')
address = address_tmp.split('\r\n')[3].split()[2]
answer=answer.upper()
a = "Cisco" , a.index("i") === 2
a = "Ciscoii" , a.count("i") === 3
a = "Ciscoii" , a.find("oii") === 4 no match retutrns -1
a = "Ciscoii" , a.startswith("C") === True
a = "Ciscoii" , a.endswith("q") === False
a = "Ciscoii" , "o" in a === True
a = "Ciscoii" , "o" not in a === False
"model: %s, slots %s", ("1000", "200")
a = 10, b = test, print("%d%s" % (a,b)) OP: 10test
print("{}{}".format(a,b)) OP: 10test
a = "Ciscoii" , a[1:3] === is no match retutrns -1

x = """this\
is\
test"""
type("python") = str type(123) = int
Example screenshot ---->
str(num),int(str), float(num)
list(tup), tuple(lst), set(lst)
ons
a = [], a = ["cisco", "avaya", "juniper"] a[-1] == juniper
value="check" value = [1,2,3,4,5,6]
len(value)=5 len(value)=6
for i in range(0,len(hst),3) Start = 0; End = len(hst), Step = 3
a=[1,2.3,4] , min(a) === 1
a=[1,2.3,4] , max(a) === 4
a.append(100)
del a[2]
a.pop(1)
a.remove("3")
a.insert(2,"7)"
b = [9, 99, 999] a.extend(b)
a.sort()
a.reverse()
sorted(a)
sorted(a, reverse = True)
set(a), set([10, 20, 10]) == 10, 20
a.intersection(b)
a.difference(b)
a.union(b)
a.clear()
c = (1,2.3,4,5), c[0] === 1
device === Cisco
tup=("Cisco", "2600")
(device, model) = tup
OR
("Cisco", "2600") = (device, model)
a = { "Vendor" : "Cisco", "Model" : "100" } a["Vendor"] == Cisco
range(5) === 0,1,2,3,4
vendors = ["Cisco", "HP", "Avaya", "Juniper"]
for elem in range(len(vendors)):
Print(vendors[elem])

Functions

Here we have 2 groups as highlighted


in red.
el.group(0)=Hostname, 'abc'; 'def'
line="Hostname: ['abc'; 'def']" el.group(1)=Hostname
el=re.search("([A-Za-z ]+): \[(.+)\]", line) el.group(2)='abc'; 'def'
a = re.match("You", mystr) === sre.SRE_Match object at 0xb74d1f38
a.group === YOU

macadd = re.findall('[a-zA-Z0-9]+\.[a-zA-Z0-9]+\.[a- 10bd.1800.2187


zA-Z0-9]+', res[n]) GigabitEthernet2/44
pt = re.findall('[a-zA-Z0-9]+/[0-9]*', res[n])
tions
sys.exit()

class test(object):
def _testfun(self):
print("Hi") Here the output is "Hi"
def testfun1(self):
self._testfun()

t = test()
t.testfun1()
class test(object):
def __testfun(self):
print("From Class test")
def testfun(self):
self.__testfun()

class test1(test):
def __testfun(self):
print("From Class test1") Here the output is "From Class test"

t = test1()
t.testfun()

class FalseCalculator(object):

name = "test string" def __init__(self, number):


name.__len__() self.number = number
11
number = FalseCalculator(20)

from foo import *

poo.py print bar


print baz
__all__ = ['bar', 'baz']
# The following will trigger an
waz = 5 exception, as "waz" is not exported by
bar = 10 the module
def baz(): return 'baz' print waz

strftime("%a, %d %b %Y %X +0000", gmtime()) Tue, 06 Jan 2009 04:54:56 +0000


tions
$ pip install paramiko $ pip install flask-restful
$ pip install netmiko $ pip install ansible
import paramiko, help(paramiko)
>>> dir(paramiko)
['AUTH_FAILED',
dir(paramiko) 'AUTH_PARTIALLY_SUCCESSFUL',
a = 10, id(10) = 153993284 'AUTH_SUCCESSFUL', 'Agent',
'AgentKey', 'AuthHandler',
'AuthenticationException',
ons 'AutoAddPolicy', 'BadAuthenticati
myFile = open("test.txt", "r")

myFile.seek(0) === Bring cursor to begin


myFile.tell() === 0L(File beginning)
myFile.read(5)
myFile.readline()
for line in myFile.readlines():
if line.startswith("A"):
print(line)
set python package path

from __future__ import print_function

Using Paramiko for SSH

Using Netmiko for SSH

Install Python from GItHub

Create a Python package


Using Strip,max,int functions

List Declaration

__main__

*args and **kwargs

To sort date that are stored in list


To read data from excel and load in the
database

Set in jinja

To install PIL
To get form values with same field name

Check package version

Create a virtual environment

convert excel to json


Type "python"
import sys
print(sys.path)
sys.path.insert(0, "/home/cchinni/paramiko-2.1.2")
print(sys.path)
Note: The path will be displayed with paramiko in its.

import os
import getpass
import paramiko
import socket
import re
import sys

#username = input('Enter username for device login:')

def enterPassword():
from __future__ import print_function
whilenetmiko
from True: # import
repeat ConnectHandler
forever
password
import sys = getpass.getpass('Enter corresponding password:')
password_again
import time = getpass.getpass('Confirm password:')
if password
import select != password_again:
importprint('Password
paramiko and confirmation do not match.Please try again!!')
else: re
import
fd =return password
open(r'output.doc','w') # Where you want the file to save to.
#password = enterPassword()
old_stdout sys.stdout
sys.stdout = fd
platform = 'cisco_ios'
# Opens file
username in read mode
= 'username' # edit to reflect
f1 = open('devices.txt','r')
password = 'password' # edit to reflect
cd
f2 =\ open('commandfile.txt','r')
curl -k https://sgithub.fr.world.socgen/raw/CDPlatformPython/python-configuration/master/install.sh
#ip_add_file
Creates list= based on f1
open(r'devices.txt','r') # a simple list of IP addresses you want to connect to each one on >>install.sh
a new line
chmod
devices777 install.sh
= f1.readlines()
./install.sh
commands
for = f2.readlines()
host in ip_add_file:
vim
data .bashrc
host=[]= host.strip()
export
output
device = []
= ConnectHandler(device_type=platform, ip=host, username="admin", password="admin", port=2024)
PATH=/home/kcj/tools/python/bin:/NSODEVAP006/home/kcj/ncs44/bin:/usr/local/bin:/usr/bin:/usr/local/sbin:/usr/sbin:/opt/
output = device.send_command('terminal length 0')
bs/bin
foroutput
device=indevice.send_command('enable')
devices: #Editable to be what ever is needed
export
device LD_LIBRARY_PATH=/home/kcj/tools/python/lib
= device.rstrip()
print('##############################################################\n')
bash
for command in commands:
print('...................CISCO COMMAND SHOW RUN OUTPUT......................\n')
source
output .bashrc
command = command.rstrip()
= device.send_command('show running-config devices device c0 address')
pythonssh = paramiko.SSHClient()
print(output)
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
print('##############################################################\n')
ssh.connect(device, username="admin",
print('...................CISCO COMMAND SHOWpassword="admin", port=2024)
IP INT BR OUTPUT......................\n')
stdin,
#output stdout,
= stderr = ssh.exec_command(command)
device.send_command('sh ip int br')
Create python files in a folder, for example test1.py, test2.py,test3.py in "Test" folder
output_tmp
one more =file
#print(output)
Create stdout.read()
"__int__.py" in "Test" folder and add the below lines:
output = output_tmp.decode().split('\r\n')
print('##############################################################\n')
from test1 import test1
fromdata.append(device)
test2 import test2
fromdata.append(command)
fd.close()
test3 import test3
Afterdata.append("*************************************************************************")
you add these lines to __init__.py, you have all of these classes available when you import the "Test" package.
importforTest
line in output:
data.append(line)
ssh.close()
f1.close()
f2.close()

f = open("output.doc", "w")
f.write("\n".join(map(lambda x: str(x), data)))
f.close()
TODOS = { 'todo1': {'task': 'build an API'},
'todo2': {'task': '?????'},
'todo3': {'task': 'profit!'}, }
args = parser.parse_args()
todo_id = int(max(TODOS.keys()).lstrip('todo')) + 1
todo_id = 'todo%i' % todo_id
TODOS[todo_id] = {'task': args['task']}
return TODOS[todo_id], 201

You cannot assign to a list like lst[i] = something


Try this instead:
lst = [None] * 10

The above will create a list of size 10, where each position is initialized to None. After that, you can add elements to it:
lst = [None] * 10
for i in range(10):
lst[i] = i

Admittedly, that's not the Pythonic way to do things. Better do this:


When
lst = [] the Python interpreter reads a source file, it executes all of the code found in it.
for i in temp:
Before executing the code, it will define a few special variables. For example, if the python interpreter is running that module (
lst.append(i)
source file) as the main program, it sets the special __name__ variable to have a value "__main__". If this file is being imported
another module, __name__ will be set to the module's name

*args and **kwargs allow you to pass a variable number of arguments to a function. What does variable mean here is that you
know before hand that how many arguments can be passed to your function by the user so in this case you use these two keyw
*args is used to send a non-keyworded variable length argument list to the function. Here’s an example to help you get a clear
def test_var_args(*argv):
for arg in argv:
print "another arg through *argv :", arg

test_var_args('yasoob','python','eggs','test')

**kwargs allows you to pass keyworded variable length of arguments to a function. You should use **kwargs if you want to ha
named arguments in a function. Here is an example to get you going with it:
def greet_me(**kwargs):
if kwargs is not None:
for key, value in kwargs.iteritems():
print "%s == %s" %(key,value)

>>> greet_me(name="yasoob")
d = ['09-2012', '04-2007', '11-2012', '05-2013', '12-2006', '05-2006', '08-2007']
d1 = sorted(d, key=lambda x: datetime.datetime.strptime(x, '%m-%Y'))
import xlrd
workbook = xlrd.open_workbook("/NSODEVAP005/home/cchinni/lab/intrasec_final/intrasec/source/database/Firewall_Detail
sh = workbook.sheet_by_name("colors")
n=0
i=0
for n in range(sh.nrows):
envdata = sh.cell_value(n, 0)
clrdata = sh.cell_value(n, 1)
setenv = EnvInventory(env=envdata, color=clrdata)
self.db.session.add(setenv)
self.db.session.commit()

{% set cnt = [0] %}


{% for room in rooms %}
{% for bed in room %}
{% if cnt.append(cnt.pop() + 1) %}{% endif %}
{% endfor %}
{{ cnt[0] }}
{% endfor %}
total times through = {{ cnt[0] }}
pip install python-resize-image
request.form.getlist('dca')
import openpyxl
print(openpyxl.__version__)
$ virtualenv drf_sample
$ cd drf_sample
$ . bin/activate
(drf_sample) [cchinni@nsodevap005 drf_sample]$

def parse_data(data):
workbook = xlrd.open_workbook(data.get('filePath'))
worksheet = workbook.sheet_by_name(data.get('sheetName'))

data = []
keys = [rows.value for rows in worksheet.row(0)]
for row_number in range(worksheet.nrows):
if row_number == 0:
continue
row_data = {}
for col_number, cell in enumerate(worksheet.row(row_number)):
row_data[keys[col_number]] = str(cell.value).strip()
data.append(row_data)
return data
output_tmp = stdout.read()
Issue output = output_tmp.split('\r\n')
Error: a bytes like object is required, not str

This error will come with split function in 3.x version


Fix Use decode() and modify the code as below:
output = output_tmp.decode().split('\r\n')
TypeError: command() takes 0 positional arguments but 1 was given
Issue

command method needs 'self' as a parameter, since it is a class method and not a
Fix function.
So modify command() to command(self)

Anda mungkin juga menyukai