Python syntax template (common)

Keywords: Python encoding

Catalog

1. How to store data

  • Variable: age =10
  • String: name = "python"
  • List: [1,2,3,"python"]
  • Tuple: (1,2,3) (cannot be changed)
  • Dictionary: {"a":100, "b":"666"}

2. How to use data

  • Number operators: +, -, *, /,%, / /**
  • Judgment cycle:
    • if judgement:
    if a>10:
    b = a + 20
    if b>20:
      pass
    elif: a>8:
    pass
    else:
    pass
    • while Loop
while i<5:
  # do something
  pass
  i = i + 1

while true:
  pass

3. function

# Position parameter  
def person(name, age):
  print(name,age)

# Default parameters  

def person(name,age=20):
  print(name, age)

# Key parameters
def person(name, age, **kw):
    print('name:', name, 'age:', age, 'other:', kw)  

person('hao', 20) # name: Michael age: 30 other: {}
person('hao', 20, gener = 'M', job = 'Engineer') # name: Adam age: 45 other: {'gender': 'M', 'job': 'Engineer'}  
extra = {'city': 'Beijing', 'job': 'Engineer'}
person('Jack', 24, **extra)  

# Named key parameters
def person(name, age, *, city='Beijing', job):
    print(name, age, city, job)

person('Jack', 24, job = '123')
person('Jack', 24, city = 'Beijing', job = 'Engineer')

# Combination
# Variable + key parameter
def f1(a, b, c=0, *args, **kw):
    print('a =', a, 'b =', b, 'c =', c, 'args =', args, 'kw =', kw)

f1(1, 2, 3, 'a', 'b')   # a = 1 b = 2 c = 3 args = ('a', 'b') kw = {'x': 99}
f1(1, 2, 3, 'a', 'b', x=99) # a = 1 b = 2 c = 0 d = 99 kw = {'ext': None}

# Default parameter + named key parameter + key parameter
def f2(a, b, c=0, *, d, **kw):
    print('a =', a, 'b =', b, 'c =', c, 'd =', d, 'kw =', kw)

f2(1, 2, d=99, ext=None) # a = 1 b = 2 c = 0 d = 99 kw = {'ext': None}

4. Classes and objects

4.1. Define the template of the class

class Student(object):
    def __init__(self, name, score):
        self.__name = name
        self.__score = score

    # print(mike)
    def __str__(self):
        msg = "name: " + self.__name + "score: " + str(self.__score)
        return msg

    # mike
    __repr__ = __str__
    # mike()
    __call__ = __str__

    @property
    def name(self):
        return self.__name

    @name.setter
    def name(self, value):
        if type(value) == str:
            self.__name = value
        else:
            raise ValueError('Bad name')

    @property
    def score(self):
        return self.__score

    @score.setter
    def score(self, value):
        if 0 <= value <= 100:
            self.__score = value
        else:
            raise ValueError('Bad score')

    def final_report(self):
        if self.__score >= 90:
            level = 'A'
        elif self.__score >= 70:
            level = 'B'
        elif self.__score >= 60:
            level = 'C'
        else:
            level = 'D'
        msg = "Your final value is: " + level
        return msg

# call

mike = Student('mike', 85)
print("-" * 20 + "Print property" + "-" * 20)
print(mike)
print("name: %s" % (mike.name))
print("-" * 30 + "Print methods" + "-" * 20)
print(mike.final_report())
print("-" * 30 + "Print modified infor" + "-" * 20)
mike.name = "Obama"
mike.score = 50
print("-" * 30)
print("modified name: %s" % (mike.name))
--------------------Print property--------------------
name: mikescore: 85
name: mike
------------------------------Print methods--------------------
Your final value is: B
------------------------------Print modified infor--------------------
------------------------------
modified name: Obama

4.2. inheritance

class SixGrade(Student):
    def __init__(self, name, score, grade):
        super().__init__(name, score)
        self.__grade = grade

    # grade is a read-only property
    @property
    def grade(self):
        return self.__grade

    def final_report(self, comments):
        # Calling the parent class in subclasses
        text_from_Father = super().final_report()
        print(text_from_Father)
        msg = "commants from teacher: " + comments
        print(msg)

print("-" * 20 + "inherit" + "-" * 20)
fangfang = SixGrade('fang', 95, 6)
fangfang.final_report("You are handsome")
print(fangfang.grade)
--------------------inherit--------------------
Your final value is: A
commants from teacher: You are handsome
6

4.3 polymorphism

class SixGrade(Student):
    pass
    
class FiveGrade(Student):
    pass
    
def print_level(Student):
    msg = Student.final_report()
    print(msg)
    
print_level(Student('from class', 90))
print_level(SixGrade('from subclass-1', 56))
print_level(FiveGrade('from subclass-2', 85))
Your final value is: A
Your final value is: D
Your final value is: B

5. IO file operation and OS directory operation

OS operation

import os
# Get the absolute path of the current directory 
path = os.path.abspath('.')
# Create a directory
os.path.join('/Users/michael', 'testdir')
os.mkdir('/Users/michael/testdir')
# Delete a directory
os.rmdir('/Users/michael/testdir')
# Split path
os.path.split('/Users/michael/testdir/file.txt')  # ('/Users/michael/testdir', 'file.txt')
os.path.splitext('/path/to/file.txt')  # ('/path/to/file', '.txt')
# rename
os.rename('test.txt', 'test.py')
# Delete files
os.remove('test.py')
# List all python files
[x for x in os.listdir('.') if os.path.isfile(x) and os.path.splitext(x)[1]=='.py']

IO file

Method Characteristic performance
read() Read all commonly
readline() Read one line at a time Minimum memory usage
readlines() Read all lines of the entire file, and save them in a list variable, each line as an element Best (enough memory)
write() Writing file
# read

# Here is the use of the read() method, where "r" stands for read
with open('testRead.txt', 'r', encoding='UTF-8') as f1:
    results = f1.read()    # Read data
    print(results)

# Here is the use of the readline() method, where "r" stands for read
with open('testRead.txt', 'r', encoding='UTF-8') as f2:
    line = f2.readline()    # Read first line
    while line is not None and line != '':
        print(line)
        line = f2.readline()    # Read next line

# Here is the use of the readlines() method, where "r" stands for read
with open('testRead.txt', 'r', encoding='UTF-8') as f3:
    lines = f3.readlines()    # receive data
    for line in lines:     # Ergodic data
        print(line)

# write

with open('/User/test.txt', 'w') as f:
  f.write('hello')

6. Use of regular expression and re module

The main references are:

6.2. Use of re module

The built-in re module uses regular expressions and provides many built-in functions:

  1. pattern = re.compile(pattern[, flag]):
  • Parameters:
    • pattern: regular in string form
    • flag: optional mode, indicating matching mode
  • Example:
import re

pattern = re.compile(r'\d+')
  1. Common methods of Pattern
import re

pattern = re.compile(r'\d+')

m0 = pattern.match('one12twothree34four')
m = pattern.match('one12twothree34four', 3, 10)

print("-" * 15 + "Match methods" + "-" * 15)
print("found strings: ", m.group(0))
print("start index of found strings: ", m.start(0))
print("end index of found strings: ", m.end(0))
print("Span length of found strigns: ", m.span(0))

s = pattern.search('one12twothree34four')

print("-" * 15 + "Search methods" + "-" * 15)
print("found strings: ", s.group(0))
print("start index of found strings: ", s.start(0))
print("end index of found strings: ", s.end(0))
print("Span length of found strigns: ", s.span(0))

f = pattern.findall('one1two2three3four4', 0, 10)

print("-" * 15 + "findall methods" + "-" * 15)
print("found strings: ", f)

f_i = pattern.finditer('one1two2three3four4', 0, 10)

print("-" * 15 + "finditer methods" + "-" * 15)
print("type of method: ", type(f_i))
for m1 in f_i:  # m1 is a Match object
    print('matching string: {}, position: {}'.format(m1.group(), m1.span()))

p = re.compile(r'[\s\,\;]+')
print("-" * 15 + "Split methods" + "-" * 15)
print("split a,b;c.d: ", p.split('a,b;; c   d'))

p1 = re.compile(r'(\w+) (\w+)')
s1 = 'hello 123, hello 456'


def func(m):
    return 'hi' + ' ' + m.group(2)


print("-" * 15 + "replace methods" + "-" * 15)
print(p1.sub(r'hello world', s1))  # Replace 'hello 123' and 'hello 456' with 'hello world'
print(p1.sub(r'\2 \1', s1))  # Reference grouping
print(p1.sub(func, s1))
print(p1.sub(func, s1, 1))  # Replace at most once

The result is:

---------------Match methods---------------
found strings:  12
start index of found strings:  3
end index of found strings:  5
Span length of found strigns:  (3, 5)
---------------Search methods---------------
found strings:  12
start index of found strings:  3
end index of found strings:  5
Span length of found strigns:  (3, 5)
---------------findall methods---------------
found strings:  ['1', '2']
---------------finditer methods---------------
type of method:  <class 'callable_iterator'>
matching string: 1, position: (3, 4)
matching string: 2, position: (7, 8)
---------------Split methods---------------
split a,b;c.d:  ['a', 'b', 'c', 'd']
---------------replace methods---------------
hello world, hello world
123 hello, 456 hello
hi 123, hi 456
hi 123, hello 456

Posted by Trojan on Tue, 10 Dec 2019 04:37:23 -0800