python

Table of Contents


List slicing

Syntax:

a[start:stop]  # items start through stop-1
a[start:]      # items start through the rest of the array
a[:stop]       # items from the beginning through stop-1
a[:]           # a copy of the whole array

One can also provide step, like:

a[start:stop:step] # start through not past stop, by step

Reference: https://stackoverflow.com/a/509295/2302094

Revision for useful functions

Method Description Syntax Reference
endswith() This returns true if the string ends with specified string else retuns false str.endswith(suffix[, start[, end]]) link

Defining Main Functions in Python

Reference: https://realpython.com/python-main-function/

Set significant figures

>>> import math
>>> format(math.pi, '.12g') # give 12 significant digits
'3.14159265359'
>>> x = 0.003143
>>> format(x, '.2g')  # give 2 significant digits
'0.0031'
>>> y = 11234
>>> format(y, '.2g')  # give 2 significant digits
'1.1e+04'
>>> y = 11234.0023
>>> format(y, '.2g')  # give 2 significant digits
'1.1e+04'
>>>

How to tar with skip some files

1
2
3
4
5
6
7
8
9
10
11
def exclude_function(filename):
if filename.endswith('.root'):
return True
else:
return False

def make_tarfile(output_filename, source_dir):
with tarfile.open(output_filename, "w:gz") as tar:
tar.add(source_dir, arcname=os.path.basename(source_dir), exclude=exclude_function)

make_tarfile("test.tgz", source/dir/path )

For loop with floats

import numpy as np
for i in np.arange(Rangelow, Rangehigh, Delta):
    print i

what getattr does?

It checks if a class has a given attribute or not? If it has given attribute then returns the value of that attribute. Else, it will give you error. Also, if you add the third argument, then, if that object is not present then it assigns that default value and return it.

class A:
    def __init__(self,x,y):
        self.x=x
        self.y=y
    def sum(self):
        return self.x+self.y
        #return x+y

obj1=A(12,10)

print (getattr(obj1,'x'))   # check if the attribute x is defined in obj1 or not. IF its defined then returns its value.
print (getattr(obj1,'y'))
print (getattr(obj1,'sum'))

print (getattr(obj1,'z',1000))

#Python Tutorial

Some Reserved Key Words

  1. split
  2. sorted
  3. help
  4. append
  5. range()

Difference between list and tuple

Concept of Dictionary

Split a Word

METHOD: split() This returns a list of all the words in the string, using str as the seperator (split on all whitespaces if left unspecified), optionally limiting the number of splits to num.

SYNTAX: str.split(str=” “, num=string.count(str)) str => this is any delimiter, by default its space num => number of lines to be made

Reference:
1. [Link1](http://www.tutorialspoint.com/python/string_split.htm)

Remove Specific Character From String

import re
line = re.sub('[!@#$]', '', line)

The characters enclosed in brackets constitute a character class. Any characters in line which are in that class are replaced with the second parameter to sub: an empty string.

Reference:
1. [Link1](http://stackoverflow.com/questions/3939361/remove-specific-characters-from-a-string-in-python)
2. [Link2](https://docs.python.org/2/library/re.html#re.sub)



Enjoy Reading This Article?

Here are some more articles you might like to read next:

  • Vi-Editor
  • ROOT CheatSheet
  • C++ CheatSheet
  • awk command
  • sed command
  • Condor Jobs
  • Git CheatSheet
  • GitLab workflow for CMS-AN
  • XDAQ Basics
  • Mac Settings
  • Grep command