一起學Python吧~基礎知識彙總

#!/bin/env python3
#-*- coding:utf8 -*-
#知識點總結
#***************print
x =3;y =4 #不推薦,還是應該寫成兩行
print('hello','world!') #逗號自動添加默認的分隔符:空格
print('hello' + 'world!') #加號表示字符拼接
print('hello','world',sep='***') #單詞間用***分隔
print('#'*50) #*號表示重複50遍
print('how are you?',end='') #默認print會打印回車,end=''表示不要回車
#***************運算符
print(5/2) #2.5
print(5//2)#丟棄餘數,只保留商
print(5 % 2)  # 求餘數
print(5 ** 3)  # 5的3次方
print(5 > 3)  # 返回True
print(3 > 5)  # 返回False
print(20 > 10 > 5)  # python支持連續比較
print(20 > 10 and 10 > 5)  # 與上面相同含義
print(not 20 > 10)  # False
#***************input
number = input("請輸入數字: ")  # input用於獲取鍵盤輸入
print(number)
print(type(number))  # input獲得的數據是字符型
print(number + 10)  # 報錯,不能把字符和數字做運算
print(int(number) + 10)  # int可將字符串10轉換成數字10
print(number + str(10))  # str將10轉換爲字符串後實現字符串拼接
username = input('username: ')
print('welcome', username)   # print各項間默認以空格作爲分隔符
print('welcome ' + username)  # 注意引號內最後的空格
#****************單雙引號
sentence = 'tom\'s pet is a cat'  # 單引號中間還有單引號,可以轉義
sentence2 = "tom's pet is a cat"  # 也可以用雙引號包含單引號
sentence3 = "tom said:\"hello world!\""
sentence4 = 'tom said:"hello world"'
# 三個連續的單引號或雙引號,可以保存輸入格式,允許輸入多行字符串
words = """
hello
world
abcd"""
print(words)
#****************list:容器 可變 序列(container variable sequence)
alist = [10, 20, 30, 'bob', 'alice', [1,2,3]]
len(alist)
alist[-1]  # 取出最後一項
alist[-1][-1]  # 因爲最後一項是列表,列表還可以繼續取下標
[1,2,3][-1]  # [1,2,3]是列表,[-1]表示列表最後一項
alist[-2][2]  # 列表倒數第2項是字符串,再取出字符下標爲2的字符
alist[3:5]   # ['bob', 'alice']
10 in alist  # True
'o' in alist  # False
100 not in alist # True

#****************tuple
atuple = (10, 20, 30, 'bob', 'alice', [1,2,3])
len(atuple)
10 in atuple #10是否在atuple裏
atuple[2]
print(atuple[3:5]) #('bob', 'alice')
# atuple[-1] = 100  # 錯誤,元組是不可變的
#********************dictionary****************
"""
字典屬於:容器、可變、映射
字典的key不能重複
字典的key必須是不可變類型
"""
# 字典是key-value(鍵-值)對形式的,沒有順序,通過鍵取出值
adict = {'name': 'bob', 'age': 23}
len(adict)       #長度
'bob' in adict  # False
'name' in adict  # True
adict['email'] = '[email protected]'  # 字典中沒有key,則添加新項目
adict['age'] = 25  # 字典中已有key,修改對應的value
#************************if判斷
if 3 > 0:
    print('yes')
    print('ok')

if 10 in [10, 20, 30]:
    print('ok')

if -0.0:
    print('yes')  # 任何值爲0的數字都是False

if [1, 2]:
    print('yes')  # 非空對象都是True

if ' ':
    print('yes')  # 空格字符也是字符,條件爲True
#**********************************條件表達式,三元運算符
a = 10
b = 20

if a < b:
    smaller = a
else:
    smaller = b

print(smaller)

s = a if a < b else b  # 和上面的if-else語句等價

print(s)
#擴展
s = a if a < b else (b if b < a else print('ok')) #可以套用
#******************for循環遍歷數據對象
astr = 'hello'
alist = [10, 20, 30]
atuple = ('bob', 'tom', 'alice')
adict = {'name': 'john', 'age': 23}

for ch in astr:
    print(ch)

for i in alist:
    print(i)

for name in atuple:
    print(name)

for key in adict:
    print('%s: %s' % (key, adict[key]))
#*************range
range(10)  # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> list(range(10))
range(6, 11)  # [6, 7, 8, 9, 10]
range(1, 10, 2)  # [1, 3, 5, 7, 9]
range(10, 0, -1)  # [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
#*****************9x9
for i in range(1, 10):
    for j in range(1, i + 1):
        print('%s*%s=%s' % (j, i, i * j), end=' ')
    print()

# i=1 ->j: [1]
# i=2 ->j: [1,2]
# i=3 ->j: [1,2,3]
#************list-analysis
# 10+5的結果放到列表中
[10 + 5]
# 10+5這個表達式計算10次
[10 + 5 for i in range(10)]
# 10+i的i來自於循環
[10 + i for i in range(10)]
[10 + i for i in range(1, 11)]
# 通過if過濾,滿足if條件的才參與10+i的運算
[10 + i for i in range(1, 11) if i % 2 == 1]
[10 + i for i in range(1, 11) if i % 2]
# 生成IP地址列表
['192.168.1.%s' % i for i in range(1, 255)]
#************************file-operation**********************
# 文件操作的三個步驟:打開、讀寫、關閉
# cp /etc/passwd /tmp
f = open('/tmp/passwd')  # 默認以r的方式打開純文本文件
data = f.read()  # read()把所有內容讀取出來
print(data)
data = f.read()  # 隨着讀寫的進行,文件指針向後移動。
# 因爲第一個f.read()已經把文件指針移動到結尾了,所以再讀就沒有數據了
# 所以data是空字符串
f.close()

f = open('/tmp/passwd')
data = f.read(4)  # 讀4字節
f.readline()  # 讀到換行符\n結束
f.readlines()  # 把每一行數據讀出來放到列表中
f.close()

################################
f = open('/tmp/passwd')
for line in f:
    print(line, end='')
f.close()

##############################
f = open('圖片地址', 'rb')  # 打開非文本文件要加參數b
f.read(4096)
f.close()

##################################
f = open('/tmp/myfile', 'w')  # 'w'打開文件,如果文件不存在則創建
f.write('hello world!\n')
f.flush()  # 立即將緩存中的數據同步到磁盤
f.writelines(['2nd line.\n', 'new line.\n'])
f.close()  # 關閉文件的時候,數據保存到磁盤

##############################
with open('/tmp/passwd') as f:
    print(f.readline())

#########################
f = open('/tmp/passwd')
f.tell()  # 查看文件指針的位置
f.readline()
f.tell()
f.seek(0, 0)  # 第一個數字是偏移量,第2位是數字是相對位置。
              # 相對位置0表示開頭,1表示當前,2表示結尾
f.tell()
f.close()
#*******************character-string******************************
py_str = 'hello world!'
print(py_str)
py_str.capitalize() #行首字母大寫
print(py_str.capitalize())
print(py_str.title()) #每個單詞首字母大寫
print(py_str.center(50)) #居中50格子默認用空格補齊
print(py_str.center(50,'#')) #居中50並且用#補全
print(py_str.ljust(50)) #左對齊右邊默認空格補全
print(py_str.rjust(50,'*')) #右對齊並以*補全左邊50
print(py_str.count('l')) #統計i出現的次數
print(py_str.count('lo'))
print(py_str.endswith('!')) #以!結尾麼?
print(py_str.endswith('d!'))
print(py_str.startswith('a')) #是以a開頭麼?
print(py_str.islower()) #字母都是小寫的?其他字符不考慮
print(py_str.isupper()) #字母都是大寫的?其他字符不考慮
print('Hao123'.isdigit())  # 所有字符都是數字嗎?
print('Hao123'.isalnum())  # 所有字符都是字母數字?
print('  \thello\t '.strip()) #默認去除兩端空白字符,常用
print('hello\t  '.lstrip()) #去除左邊
print('how are you ?'.split()) #默認分離 以空格爲分割標誌
print('hello.tar.gz'.split('.')) #分離 以·爲分割標誌
print('.'.join(['hello','tar','gz'])) #合併 是split和join是相反的
#***************************sequence-object*****************************
from random import randint

alist = list()  # []
list('hello')  # ['h', 'e', 'l', 'l', 'o']
list((10, 20, 30))  # [10, 20, 30]  元組轉列表
astr = str()  # ''
str(10)  # '10'
str(['h', 'e', 'l', 'l', 'o'])  # 將列表轉成字符串
atuple = tuple()  # ()
tuple('hello')  # ('h', 'e', 'l', 'l', 'o')
num_list = [randint(1, 100) for i in range(10)]
a = max(num_list)
i = min(num_list)
print(a,i)
#**********************character-string-format*************
"%s is %s years old" % ('bob', 23)  # 常用
"%s is %d years old" % ('bob', 23)  # 常用
"%s is %d years old" % ('bob', 23.5)  # %d是整數 常用
"%s is %f years old" % ('bob', 23.5)
"%s is %5.2f years old" % ('bob', 23.5)  # %5.2f是寬度爲5,2位小數
"97 is %c" % 97
"11 is %#o" % 11  # %#o表示有前綴的8進制
"11 is %#x" % 11
"%10s%5s" % ('name', 'age')  # %10s表示總寬度爲10,右對齊, 常用
"%10s%5s" % ('bob', 25)
"%10s%5s" % ('alice', 23)
"%-10s%-5s" % ('name', 'age')  # %-10s表示左對齊, 常用
"%-10s%-5s" % ('bob', 25)
"%10d" % 123
"%010d" % 123

a = "{} is {} years old".format('bob', 25)
b ="{1} is {0} years old".format(25, 'bob')
c = "{:<10}{:<8}".format('name', 'age')
d = "{:>10}{:>8}".format('name', 'age')
print(a) #bob is 25 years old
print(b) #bob is 25 years old
print(c) #name      age
print(d) #      name     age
#*****************shutil******************
import shutil

with open('/etc/passwd', 'rb') as sfobj:
    with open('/tmp/mima.txt', 'wb') as dfobj:
        shutil.copyfileobj(sfobj, dfobj) # 拷貝文件對象

shutil.copyfile('/etc/passwd', '/tmp/mima2.txt')
shutil.copy('/etc/shadow', '/tmp/')  # cp /etc/shadow /tmp/
shutil.copy2('/etc/shadow', '/tmp/')  # cp -p /etc/shadow /tmp/
shutil.move('/tmp/mima.txt', '/var/tmp/')  # mv /tmp/mima.txt /var/tmp/
shutil.copytree('/etc/security', '/tmp/anquan') # cp -r /etc/security /tmp/anquan
shutil.rmtree('/tmp/anquan')  # rm -rf /tmp/anquan
# 將mima2.txt的權限設置成與/etc/shadow一樣
shutil.copymode('/etc/shadow', '/tmp/mima2.txt')
# 將mima2.txt的元數據設置成與/etc/shadow一樣
# 元數據使用stat /etc/shadow查看
shutil.copystat('/etc/shadow', '/tmp/mima2.txt')
shutil.chown('/tmp/mima2.txt', user='zhangsan', group='zhangsan')
#***********************list-extent*****************
alist = [1, 2, 3, 'bob', 'alice']
alist[0] = 10
alist[1:3] = [20, 30]
alist[2:2] = [22, 24, 26, 28]
alist.append(100)
alist.remove(24)  # 刪除第一個24
alist.index('bob')  # 返回下標
blist = alist.copy()  # 相當於blist = alist[:]
alist.insert(1, 15)  # 向下標爲1的位置插入數字15
alist.pop()  # 默認彈出最後一項
alist.pop(2) # 彈出下標爲2的項目
alist.pop(alist.index('bob'))
alist.sort()
alist.reverse()
alist.count(20)  # 統計20在列表中出現的次數
alist.clear()  # 清空
alist.append('new')
alist.extend('new')
alist.extend(['hello', 'world', 'hehe'])
#******************dictionary-extend*************
adict = dict()  # {}
dict(['ab', 'cd'])
bdict = dict([('name', 'bob'),('age', 25)])
{}.fromkeys(['zhangsan', 'lisi', 'wangwu'], 11)

for key in bdict:
    print('%s: %s' % (key, bdict[key]))

print("%(name)s: %(age)s" % bdict)

bdict['name'] = 'tom'
bdict['email'] = '[email protected]'

del bdict['email']
bdict.pop('age')
bdict.clear()
#**********************dictionary-commonly used******************
adict = dict([('name', 'bob'),('age', 25)])
len(adict)
hash(10)  # 判斷給定的數據是不是不可變的,不可變數據才能作爲key
adict.keys() #提取所有key鍵
adict.values() #提取所有值value
adict.items()  #提取所有key:value
# get方法常用,重要
adict.get('name')  # 取出字典中name對應的value,如果沒有則返回None
print(adict.get('qq'))  # None(賦值不會報錯)
print(adict.get('qq', 'not found'))  # 沒有qq,返回指定內容
print(adict.get('age', 'not found'))
adict.update({'phone': '13455667788'})
#*******************set***************
# 集合相當於是無值的字典,所以也用{}表示
myset = set('hello')
len(myset)
for ch in myset:
    print(ch)

aset = set('abc')
bset = set('cde')
aset & bset  # 交集
aset.intersection(bset)  # 交集
aset | bset  # 並集
aset.union(bset)  # 並集
aset - bset  # 差補
aset.difference(bset)  # 差補
aset.add('new')
aset.update(['aaa', 'bbb'])
aset.remove('bbb')
cset = set('abcde')
dset = set('bcd')
cset.issuperset(dset)  # cset是dset的超集麼?
cset.issubset(dset)  # cset是dset的子集麼?
#****************進制轉換
hex(20) #10進制轉16
oct(10) #轉8進制
bin(10) #十進制轉2進制
# 以下備查
>>> '%#o' % 10
# 轉8進制
'0o12'
>>> '%#x' % 10
# 轉16進制
'0xa'
>>> '%f' % (5/3)
'1.666667'
>>> '%.2f' % (5/3)
# 保留2位小數
'1.67'
>>> '%5.2f' % (5/3)
# 輸出總寬度爲5,小數位2位,不夠寬度補空格
' 1.67'
>>> '%e' % 10000
'1.000000e+04'
# 科學計數法'1.000000e+04'
# 寫入非文本文件
>>> f = open('/tmp/aaaa', 'wb')
>>> hi = '你好\n'
>>> hi.encode()
b'\xe4\xbd\xa0\xe5\xa5\xbd\n' # 共寫入七個字節,在utf8編碼中一個漢字佔3字節,\n佔1字節
>>> f.write(hi.encode())
7
# 導入模塊的同時,爲模塊創建別名,不常用
>>> import getpass as gp
>>> p = gp.getpass()
Password:
#*******************os-module************
import os

os.getcwd()  # 顯示當前路徑
os.listdir()  # ls -a
os.listdir('/tmp')  # ls -a /tmp
os.mkdir('/tmp/mydemo')  # mkdir /tmp/mydemo
os.chdir('/tmp/mydemo')  # cd /tmp/mydemo
os.listdir()
os.mknod('test.txt')  # touch test.txt
os.symlink('/etc/hosts', 'zhuji')  # ln -s /etc/hosts zhuji
os.path.isfile('test.txt')  # 判斷test.txt是不是文件
os.path.islink('zhuji')  # 判斷zhuji是不是軟鏈接
os.path.isdir('/etc')
os.path.exists('/tmp')  # 判斷是否存在
os.path.basename('/tmp/abc/aaa.txt')
os.path.dirname('/tmp/abc/aaa.txt')
os.path.split('/tmp/abc/aaa.txt')
os.path.join('/home/tom', 'xyz.txt')
os.path.abspath('test.txt')  # 返回當前目錄test.txt的絕對路徑

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章