Python基礎知識1

ahfhuang發表於2018-11-15

 一、PRINT FORMATTED OUTPUT
1、%形式輸出
1.1 匹配字元,整數,浮點數(含精度),%類似轉義
print("my name is %s,age %d height %.2fm learning python progress is 3%%s." %('burton',33,1.785))
output result:

my name is burton,age 33 height 1.78m learning python progress is 3%s.

1.2 指定佔位符寬度、左右對齊和填充
print ("Name:%-10s Age:%08d Height:%8.2f"%("Aviad",25,1.833)) 
output result:

Name:Aviad      Age:00000025 Height:    1.83

1.3 有以下格式符
%s   字串 (採用str()的顯示)
%r   字串 (採用repr()的顯示)
%c   單個字元
%b   二進位制整數
%d   十進位制整數
%i   十進位制整數
%o   八進位制整數
%x   十六進位制整數
%e   指數 (基底寫為e)
%E   指數 (基底寫為E)
%f   浮點數
%F   浮點數,與上相同
%g   指數(e)或浮點數 (根據顯示長度)
%G   指數(E)或浮點數 (根據顯示長度)
%%   字元"%"

2、format形式輸出
2.1 位置傳參
li = ['burton',18,178]
print('my name is {} ,age {}'.format('burton',18))
print('my name is {1} ,age {0}'.format(18,'burton'))
print('my name is {0} ,age {1}'.format(*li))
print('name is {0[0]} age is {0[1]}'.format(li))

output result:

my name is burton ,age 18

2.2 關鍵字傳參
hash = {'name':'burton','age':18,'heigth':178}
print('my name is {name},age is {age}'.format(name='burton',age=18))
print('my name is {name},age is {age}'.format(**hash))
output result:

my name is burton ,age 18

2.3 填充與格式化
print('{0:*>8}'.format(18))   ##右對齊

******18
print('{0:*<8}'.format(18))   ##左對齊
18******
print('{0:*^8}'.format(18))  ##居中對齊
***18***

2.4 精度與進位制
print('{0:.2f}'.format(1/3))  # 0.33
print('{0:b}'.format(10))     # 1010
print('{0:o}'.format(10))     # 12
print('{0:x}'.format(10))     # a
print('{:,}'.format(1234567890)) # 1,234,567,890

3、GIve some examples

e.g.1
lst=[('lily',23,'female'),('burton',34,'male')]
for tup in lst:
    print(*tup,sep='!',end='*')           

output result:
lily!23!female*burton!34!male*


二、LOGICAL OPERATION
Priority level: not > and > or
print(True or False)                    # True
print(2 and 3)                             # 3
print(2 or 1 < 3)                          # 2
print(3 < 1 or 2 and 1)                # 1
print(not 2 > 4 and 5 or 3 < 2 and 3)  # 5

 

三、DATATYPE
1、Integer
print(int(5.1))        # 5
print(int('5'))        # 5
i = 5
print(i.bit_length())  # 3  Turn binary digits  101

2、Strings
2.1 字串常用函式
s = 'sA3 u43'
s0 = s.capitalize()           # Sa3 u43
s1 = s.title()                    # Sa3 U43
s2 = s.replace('s','w')      # wA3 u43
s31 = s.find('3',3,)           # 6   find index,from 3 to end
s32 = s.find('3',3,6)         # -1  last index
s33 = s.find('3')               # 2   times
s4 = s.center(20,'*')        # ******sA3 u43*******
s5 = s.count('3',1,4)        # 1  count substr,index from 1 to 4
s6 = s.index('u',1,5)        # 6
s7 = s.split()                   # ['sA3', 'u43'] change to list,default delimiter space
s8 = s.strip(3)                 # sA3 u4  Remove both sides matching characters,default space
s9 = s.startswith('u',4,)   # True  return Boolean type
s10 = s.endswith('2')      # False
s11 = s.upper()              # 'SA3 U43'
s12 = s.lower()               # 'sa3 u43'
s13 = '#'.join(s)              # s#A#3# #u#4#3

2.2 字串切片
s = 'abcD1efs2'
s0 = s[:]                         # abcD1efs2
s1 = s[0:]                       # abcD1efs2
s2 = s[4:-1]                    # 1efs
s3 = s[4:-1:2]                 # 1f
s4 = s[4::-1]                   # 1Dcba
s5 = s[6:0:-2]                 # f1c
s6 = s[s.index('c'):0:-1]  # cb
s7 = s[0:6:-2]                 # None

3、List
3.1 列表增刪改查
li = ['alex','wusir']
3.1.1 增加列表
li.append('burton')        # ['alex', 'wusir', 'burton']
li.insert(1,'lina')             # ['alex', 'lina', 'wusir']
li.extend('boy')              # ['alex', 'wusir', 'b', 'o', 'y']
3.1.2 刪除列表
name = li.pop(0)
print(name,li)               # alex ['wusir']   預設刪除最後一個
li.remove('alex')           # ['wusir']     按元素去刪除
li.clear()                       # 清空
del li                            # 刪除列內容和定義
del li[1:]                       # ['alex']  切片去刪除
3.1.3 修改列表
li[0] = [1,'burton']        # [[1, 'burton'], 'wusir']
li[0:2] = [1,'burton','jm'] # [1, 'burton','jm']
3.1.4 查詢列表
for i in li:
    print(i)                # alex wusir
print(li[0:2])              # ['alex', 'wusir']

3.2 公共方法
li = [1,5,6,2,5]
l = len(li)                        # 5
num = li.count(5)           # 2
num = li.index(5)           # 1
l1 = li.sort()                    # None 順序,只針對原列表
l2 = li.reverse()              # None 倒序,只針對原列表
lst = ['alex','wusir']
s = '+'.join(lst)                # 得到字串 alex+wusir

3.3 特殊列表
for i in range(2,5)           # 2 3 4
for i in range(3)              # 0 1 2
for i in range(0,10,3)      # 0 3 6 9
for i in range(7,0,-2)      # 7 5 3 1

3.4 列舉
list1 = [1,2,33]
for i, v in enumerate(list1):
    print(i, ":", v)
result:
0 : 1
1 : 2
2 : 33

3.5 遍歷所有的元素
li = [1,2,3,5,'alex',[2,3,4,5,'taibai'],'afds']
for i in range(len(li)):
    if type(li[i]) == list:
#   if isinstance(li[i],list):
        for j in li[i]:
            print(j)
    else:print(li[i])

3.6 去重複值:
def del_duplicates(values):
    if len(values) == 0:
         return False
    lst = []
    lst.append(values[0])
    for i in range(1,len(values)):
        if values[i] in lst:
            continue
        else:
            lst.append(values[i])
    return lst
print(del_duplicates([20,30,20,40,30]))
4、tuple(只讀列表,可迴圈查詢,可切片,兒子不能改,孫子可能可以改)
tu = (1,'alex',[3,4,'taibai'])
tu[2][2]                    # taibai
tu[2][2]=tu[2][2].upper()   # TAIBAI 轉成大寫
for i in tu:
    print(i)                # 檢視元祖

5、Dictionary
dic1 = {'age': 18, 'name': 'jin'}
5.1 增加字典
dic1['height'] = 185                    # 對沒有鍵值新增,有鍵值的覆蓋
dic1.setdefault('weight')             # 沒有鍵值,預設為None
dic1.setdefault('weight',150)      # 位置隨機
dic1.setdefault('name','burton')  # 有鍵值不新增

5.2 刪除字典
dic1.pop('age')                       # 18
dic1.pop('sex',None)             # 沒key就會報錯,避免該問題可設定返回值
dic1.popitem())                     # 隨機刪除 有返回值 元組裡面是刪除的鍵值。
del dic1['name']                    # 刪字典內容,如沒對應key報錯
del dic1                                # 刪整個字典
dic1.clear()                          #清空字典

5.3 修改字典
dic1['age'] = 16                    # 原來有的key
dic2 = {"name":"alex","weight":75}
dic2.update(dic)                  # 原來有key修改,沒有增加

5.4 查詢字典
print(dic1.items())                #列印出是個列表
for i in dic1.keys()
for i in dic1.values()
for k,v in dic1.items()
dic1.get('name1','no key')    # 沒匹配就返回空,如有第二個引數,返回第二個引數

5.5 例子
def element_times(values):
    if len(values) == 0:
        return False
    dic = {}
    for i in range(0,len(values)):
        if str(values[i]) in dic:
            dic[str(values[i])] += 1
        else:
            dic[str((values[i]))] = 1
    return dic
print(element_times([40,30,30,20,40,30,40]))

output result:
{'20': 1, '40': 3, '30': 3}

6、set
set1 = set({1,2,3})
set1 = {1,2,3}                       #元素是不可雜湊

6.1 insert set content
set1.add('burton')                 # {1,2,3,'burton'}
set1.update('abc')                # {1,2,3,'abc'}

6.2 delete set content
set1.pop()                            # 隨機刪除
print(set1.pop())                   # 有返回值
set1.remove(2)                    # 按元素
set1.clear()                          # set()
del set1

6.3 intersection and union and so.
set1 = {2,3,4}
set2 = {4,5,6}
print(set1 & set2)                # {4}
print(set1.intersection(set2))    # {4}
print(set1 | set2)                # {2, 3, 4, 5, 6}
print(set2.union(set1))           # {2, 3, 4, 5, 6}
print(set1 ^ set2)                # {2, 3, 5, 6}
print(set1.symmetric_difference(set2))  # {2, 3, 5, 6}
print(set1 - set2)                # {2, 3}

6.4 Give some examples

e.g.1 ### remove duplicate values
li = [1,2,33,33,2,1,4,5,6,6]
set1 = set(li)
li = list(set1)
print(li)


四、FILES
1、read file
The testfile.txt file is stored in 'abc'
e.g.1 # 'r' read mode
f = open('testfile.txt',mode='r',encoding='utf-8')
content = f.read()
print(content)
f.close()                     
# must close the file after used
result: abc

with open('testfile.txt',mode='r',encoding='utf-8') as f:
     print(f.read())          # needn't close the file
output result: abc

e.g.2 # 'r+b' read mode
f = open('testfile.txt',mode='r+b')
content = f.read()
f.close()
print(content)
output result: b'abc'

e.g.3 # '你好' in file
f = open('testfile.txt',mode='r+b')
print(f.read())
f.write('大猛'.encode('utf-8'))
f.close()
output result: print b'\xe4\xbd\xa0\xe5\xa5\xbd' ,'你好大猛' in file

e.g.4 # 'r+' read mode,'abc' in file
f = open('testfile.txt',mode='r+',encoding='utf-8')
content = f.read()
print(content)
f.write('ABC')
f.close()
output result: print 'abc' , 'abcABC' in file

e.g.5 # We change the order of reading and writing,'abc' in file
f = open('testfile.txt',mode='r+',encoding='utf-8')
f.write('ABC')
content = f.read()
print(content)
f.close()
output result: print None , 'ABC' in file

2、write file
e.g.1 # 'abc' in file
f = open('testfile.txt',mode='r',encoding='utf-8')
f.write('DBA')
f.close() 
result:'DBA'  # The file content will be recover by 'DBA'

e.g.2 # 'abc' in file
f = open('testfile.txt',mode='w+',encoding='utf-8')
f.write('aaa')
f.seek(0)
print(f.read())
f.close()
result:print 'aaa','aaa' in file

e.g.3 # 'wb'mode
f = open('testfile.txt',mode='wb')
f.write('佳琪'.encode('utf-8'))
f.close()
result:'佳琪' in file

e.g.4 # 'abc' in file
f = open('testfile.txt',mode='a+',encoding='utf-8')
f.write('佳琪')
f.seek(0)            #move cursor position
print(f.read())
f.close()
output result:print 'abc佳琪',also 'abc佳琪' in file

3、Other function
print(f.tell())      # tell you where is cursor position
f.truncate(4)
f.readlines()        # Read files line by line

4、 Give some examples

e.g.1
# 'abc\nABC' in file
with open('testfile.txt',mode='r',encoding='utf-8') as f:
      for i in f.readlines()
          print(i)
outputresult:

abc 
ABC

 

五、FUNCTION
1、Description function
def func():
    '''
    You can describe what function is implemented.
    How to use parameter values
    what return
    '''
    pass

2、How to use function
e.g.1
def sum(a,b=2,*args):
    total = a +b
    for i in args:
        total += i
    return total
print(sum(1,4,9,10))         #24
print(sum(2))                    #4

e.g.2
def func1(a,b=1,**kvargs):
    print(a,b,kvargs)

func1(3,4,x=4,y=5)           # 3 4 {'x': 4, 'y': 5}

e.g.3
def func2(*args,**kvargs):
    print(args,kvargs)

func2('a',1,x=3,y=2)         # ('a', 1) {'y': 2, 'x': 3}

e.g.4
def func3(a,*args):
    total = a
    for i in args:
        total += i
    return total

li = [1,3,5,7,9]
print(func3(*li))             # 25

3、遞迴函式

e.g.5 #斐波那契數列 1,1,2,3,5,8,13,21,34,55

#mothed 1
def fun(n):
    if n == 1:
        return 1
    if n == 2:
        return 1
    return fun(n-1) +fun(n-2)
print(fun(6))            # 8 這樣寫效率很差

#mothed 2

def fib(n,a=1,b=1):
    if n==1 : return a
    return fib(n-1,b,a+b)
print(fib(6))              # 8 這樣寫效率高

4、變數作用域
e.g.6 # nolocal 一般是用在閉包函式裡
x = 123
def outer():
    x = 100
    def inter():
        nonlocal x
        x = 200
    inter()
    print(x)
outer()
output result: 200

e.g.7 # global全域性變數
x = 123
def testglobal():
    global x
    print(x)
    x = 100
    print(x)
testGlobal()
print(x)
output result:
123
100
100

5、Give some examples
e.g.8 # 登入驗證
my_script1.py
def judgment(user,li=[]):
    for i in range(len(li)):
       if user in li[i].keys():
         return 1
    if not user.isalnum() and user[0].isdigit():
         return 2
    return 3

def register(user,pswd,li=[]):
    li.append({user:pswd})
    return li

li = [{'lina': '342'}, {'burton': '223'}]
flag = True
i = 0
while i < 3:
    usernm = input("Please enter username:")
    if judgment(usernm,li) == 1:
        print('該賬號已被註冊,請重新輸入賬號。')
        i += 1
        continue
    elif judgment(usernm,li) == 2:
        print('輸入的賬號只能數字和字母,且不能數字開頭!')
        i += 1
        continue
    else:
        passwd = input("Please enter password:")
        register(usernm,passwd,li)
        break
else:
    print('你沒有機會了!')
print(li)


e.g.9 # 隨機資料和字母驗證碼
# def ger_verif(arg):
#     l=[]
#     for i in range(48,58):
#         l.append(chr(i))
#     for i in range(65,91):
#         l.append(chr(i))
#     for i in range(97,123):
#         l.append(chr(i))
#     lst = random.sample(l,arg)
#     print(''.join(lst))
#     return ''.join(lst)
def ger_verif(arg):
    s=""
    for i in range(0,arg):
        cur = random.randint(0,5)
        if cur > 2:
            cur = chr(random.randint(65,90))
        elif i < 2:
            cur = chr(random.randint(97,122))
        else:
            cur = chr(random.randint(48,57))
        s += cur
    print(s)
    return s
def verification():
    num = 3
    gere = ger_verif(6)
    while num > 0:
        str = input('Please enter code:')
        if len(str) == 0:
            return 0
        if gere.upper() != str.upper():
            num -= 1
            print('Please enter correctly verification!')
        else:
            return 1
    return 0
ret = verification()
print(ret)

 

六、REGULAR KNOWLEDGE POINT
http://tool.chinaz.com/regex/    測試網站
https://www.regexpal.com/ (正則線上匹配)
1、Cheat Sheet
1.1 Character classes
.                 # any character except newline
\w \d \s       # word, digit, whitespace
\W \D \S     # not word, digit, whitespace
[abc]          # any of a, b, or c
[^abc]        # not a, b, or c
[a-g]          # character between a & g

1.2 Anchors
^abc$        # start / end of the string
\b              # word boundary

1.3 Escaped characters
\. \* \\         # escaped special characters
\t \n \r        # tab, linefeed, carriage return
\u00A9      # unicode escaped

1.4 Groups & Lookaround
(abc)         # capture group
\1              # backreference to group #1
(?:abc)      # non-capturing group
(?=abc)     # positive lookahead
(?!abc)      # negative lookahead

1.5 Quantifiers & Alternation
a* a+ a?    # 0 or more, 1 or more, 0 or 1
a{5} a{2,}   # exactly five, two or more
a{1,3}        # between one & three
a+? a{2,}? # match as few as possible
ab|cd         # match ab or cd

2、 Give some examples

e.g.1
str1 = 'chinese&people'
ret = re.findall('(?<=chinese)\Wpeople',str1)        # &people
ret1 = re.findall('chinese\W(?=people)',str1)        # chinese&
ret2 = re.findall('(?<!=japanese)\Wpeople',str1)   # &people
ret3 = re.findall('chinese\W(?!=man)',str1)           # chinese&
ret4 = re.sub('\B(?=(?:\d{3})+(?!\d))',',','1234567890')   #1,234,567,890  ???

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/30590361/viewspace-2220111/,如需轉載,請註明出處,否則將追究法律責任。

相關文章