Python基础知识1

 一、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  ???

    原文作者:ahfhuang
    原文地址: http://blog.itpub.net/30590361/viewspace-2220111/
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞