Python學習00-Tips

查看所有Python相關學習筆記

此篇文章用于記錄學習過程中接觸到的零散知識點(包含已歸納到各個模塊的知識點)。
用于自我查詢--->>備忘錄

  • 開方

    x**2 
    > 等于x的平方
    x**3
    > 等于x的三次方
    
  • 取整

    >>>int(3.44)
    3
    >>> int(3.9)
    3
    
  • 四舍五入

    round(number,digits)
    

    number,要四舍五入的數(shù),digits是要小數(shù)點后保留的位數(shù)

    • 如果 digits 大于 0,則四舍五入到指定的小數(shù)位。
      round(13.2222,1) > 13.2
    • 如果 digits 等于 0,則四舍五入到最接近的整數(shù)。
      round(13.2222,0) > 13.0
    • 如果 digits 小于 0,則在小數(shù)點左側(cè)進行四舍五入。
      round(13.2222,-1) > 10.0
      round(15.2222,-1) > 20.0
      round(15.2222,-2) > 0.0
    • 如果round函數(shù)只有參數(shù)number,等同于digits 等于 0。
      round(13.2222) > 13
  • 使用方法修改字符串的大小寫

    • upper()將所有字母變?yōu)榇髮戄敵?/li>
    • lower()將所有字母變?yōu)樾戄敵?/li>
    • capitalize() 首字母大寫,其余小寫
    • title() 所有單詞首字母大寫,其余小寫
      >>>s = 'hEllo pYthon'
      >>>print(s.upper())
      >>>print(s.lower())
      >>>print(s.capitalize())
      >>>print(s.title())
      HELLO PYTHON
      hello python
      Hello python
      Hello Python
      
    • Python提供了isupper(),islower(),istitle()方法用來判斷字符串的大小寫
      >>>print('A'.isupper())
      >>>print('A'.islower())
      >>>print('Python Is So Good'.istitle())
      >>># print('Dont do that!'.iscapitalize())#錯誤,不存在iscapitalize()方法
      True
      False
      True
      
  • 刪除空白【strip-刪除,清除】

    • rstrip()刪除末尾的空白(包括\t和\n)
    • lstrip()刪除頭部的空白(包括\t和\n)
    • strip()刪除字符串兩端的空白(包括\t和\n)
      >>>msg='   python   '
      >>>print('-'+msg+'-')#初始狀態(tài)
      >>>print('-'+msg.rstrip()+'-')#刪除右側(cè)空格
      >>>print('-'+msg.lstrip()+'-')#刪除左側(cè)空格
      >>>print('-'+msg.strip()+'-')#刪除兩側(cè)空格
      -   python   -
      -   python-
      -python   -
      -python-
      
  • 使用方法sort()對列表進行永久排序-按字母排序

    #正序
    >>>nicks = ['zhangsan','lisi','wangwu','zhaoliu']
    >>>print(nicks)#原始狀態(tài)
    >>>nicks.sort()
    >>>print(nicks)#排序后的狀態(tài)
    ['zhangsan', 'lisi', 'wangwu', 'zhaoliu']
    ['lisi', 'wangwu', 'zhangsan', 'zhaoliu']
    
    #倒序
    >>>nicks = ['zhangsan','lisi','wangwu','zhaoliu']
    >>>print(nicks)#原始狀態(tài)
    >>>nicks.sort(reverse = True)
    >>>print(nicks)#排序后的狀態(tài)
    ['zhangsan', 'lisi', 'wangwu', 'zhaoliu']
    ['zhaoliu', 'zhangsan', 'wangwu', 'lisi']
    
  • 使用方法sorted()對列表進行臨時排序-按字母排序

    >>>nicks = ['zhangsan','lisi','wangwu','zhaoliu']
    >>>print(nicks)#原始狀態(tài)
    >>>print(sorted(nicks))#臨時排序的狀態(tài)(正序)
    >>>print(sorted(nicks,reverse = True))#臨時排序的狀態(tài)(倒序)
    >>>print(nicks)#使用臨時排序后,nicks的狀態(tài)
    ['zhangsan', 'lisi', 'wangwu', 'zhaoliu']
    ['lisi', 'wangwu', 'zhangsan', 'zhaoliu']
    ['zhaoliu', 'zhangsan', 'wangwu', 'lisi']
    ['zhangsan', 'lisi', 'wangwu', 'zhaoliu']
    
  • 倒著打印列表,按元素反轉(zhuǎn)列表排序

    >>>nicks = ['zhangsan','lisi','wangwu','zhaoliu']
    >>>print(nicks)#原始狀態(tài)
    >>>nicks.reverse()#倒轉(zhuǎn)
    >>>print(nicks)#倒轉(zhuǎn)后的狀態(tài)
    ['zhangsan', 'lisi', 'wangwu', 'zhaoliu']
    ['zhaoliu', 'wangwu', 'lisi', 'zhangsan']
    
  • 方法zfill()在數(shù)值字符串前填充0

    >>>'12'.zfill(5)
    '00012'
    >>>'-3.14'.zfill(7)
    '-003.14'
    >>>'3.14159265359'.zfill(5)
    '3.14159265359'
    
  • math模塊為浮點運算提供了對底層C函數(shù)庫的訪問

    >>> import math
    >>> math.cos(math.pi / 4.0)
    0.70710678118654757
    >>> math.log(1024, 2)
    10.0
    
  • random提供了生成隨機數(shù)的工具

    >>> import random
    >>> random.choice(['apple', 'pear', 'banana'])
    'apple'
    >>> random.sample(range(100), 10)   # sampling without replacement
    [30, 83, 16, 4, 8, 81, 41, 50, 18, 33]
    >>> random.random()    # random float
    0.17970987693706186
    >>> random.randrange(6)    # random integer chosen from range(6)
    4
    >>>random.randint(1,11) #隨機生成一個數(shù)(包含開始和結束的數(shù)字)
    
  • range

    語法:range([start,]stop[,step=1])
    - 這個BIF有三個參數(shù),其中用中括號括起來的兩個表示這兩個參數(shù)是可選的
    - step=1表示第三個參數(shù)的默認值是1
    - range這個BIF的作用是生成一個從start參數(shù)的值開始到stop參數(shù)的值結束的數(shù)字序列(包括start參數(shù)哦的值,不包括stop參數(shù)的值)

    >>> for i in range(4):
    ...     print(i,end=' ')
    ... 
    0 1 2 3 
    >>> for i in range(0,4,2):
    ...     print(i,end=' ')
    ... 
    0 2 
    
  • datetime 模塊為日期和時間處理同時提供了簡單和復雜的方法。支持日期和時間算法的同時,實現(xiàn)的重點放在更有效的處理和格式化輸出。該模塊還支持時區(qū)處理。

    >>> # dates are easily constructed and formatted
    >>> from datetime import date
    >>> now = date.today()
    >>> now
    datetime.date(2003, 12, 2)
    >>> now.strftime("%m-%d-%y. %d %b %Y is a %A on the %d day of %B.")
    '12-02-03. 02 Dec 2003 is a Tuesday on the 02 day of December.'
    
    >>> # dates support calendar arithmetic
    >>> birthday = date(1964, 7, 31)
    >>> age = now - birthday
    >>> age.days
    14368
    
  • Python中的split()函數(shù)的用法

    • Python中有split()和os.path.split()兩個函數(shù),具體作用如下:

      • split():拆分字符串。通過指定分隔符對字符串進行切片,并返回分割后的字符串列表(list)
      • os.path.split():按照路徑將文件名和路徑分割開
    • 1、split()函數(shù)

      語法:str.split(str="",num=string.count(str))[n]

    • 參數(shù)說明:

      • str:表示為分隔符,默認為空格,但是不能為空('')。若字符串中沒有分隔符,則把整個字符串作為列表的一個元素
      • num:表示分割次數(shù)。如果存在參數(shù)num,則僅分隔成<font color=red>num+1</font> 個子字符串,并且每一個子字符串可以賦給新的變量
      • n:表示選取第n個分片

      注意:當使用空格作為分隔符時,對于中間為空的項會自動忽略

    • splitlines() 以換行符分割字符串

      >>>fh = open('abc.txt')
      >>>flines = fh.read().splitlines()
      >>>lines
      
    • 2、os.path.split()函數(shù)

      語法:os.path.split('PATH')

    • 參數(shù)說明:

      • PATH指一個文件的全路徑作為參數(shù):
      • 如果給出的是一個目錄和文件名,則輸出路徑和文件名
      • 如果給出的是一個目錄名,則輸出路徑和為空文件名
    • 3、分離字符串

      string = "www.gziscas.com.cn"

      • 1.以'.'為分隔符
        >>>print(string.split('.'))
        ['www', 'gziscas', 'com', 'cn']
        
      • 2.分割兩次
        >>>print(string.split('.',2))
        ['www', 'gziscas', 'com.cn']
        
      • 3.分割兩次,并取序列為1的項
        >>>print(string.split('.',2)[1])
        gziscas
        
      • 4.分割兩次,并把分割后的三個部分保存到三個文件
        >>>u1, u2, u3 =string.split('.',2)
        >>>print(u1)
        >>>print(u2)
        >>>print(u3)
        www
        gziscas
        com.cn
        
    • 4、分離文件名和路徑

       ```
       >>>import os
       >>>print(os.path.split('/dodo/soft/python/'))
       ('/dodo/soft/python', '')
       >>>print(os.path.split('/dodo/soft/python'))
       ('/dodo/soft', 'python') 
       ```
      
  • 切片賦值

    >>>a = [123,'abc',4.56,['test1','test2']]
    >>>print(a)
    >>>a[1:3] =[1,2]
    >>>print(a)
    [123, 'abc', 4.56, ['test1', 'test2']]
    [123, 1, 2, ['test1', 'test2']]
    
    
  • 字符串對象的常用方法

    • count 計算字符串中包含的多少個指定的子字符串
      >>> '123 123 789'.count('123')
      2
      
    • endswith 檢查字符串是否以指定的字符串結尾
      >>>'139 123 789'.endswith('89')
      True
      
    • startswith 檢查字符串是否以指定的字符串開頭
      >>>'185 123 789'.startswith('123')
      False
      
    • find 返回指定的子字符串在字符串中出現(xiàn)的位置
      >>> '12345678'.find('4566')
      3
      
      • 如果有多個,返回第一個的位置
        >>>'ok,good,name'.find(',')
        2
        
      • 還可以指定從什么位置開始查找
        >>>'ok,good,name'.find(',',3)
        7
        
      • isalpha 檢查字符串中都是字母
        >>>'abc1'.isalpha()
        False
        
      • isdigit 檢查字符串中是否都是數(shù)字
        >>>'abc1'.isdigit()
        False
        
      • str.join 將sequence類型的參數(shù)的元素字符串合并(連接)到一個字符串,string作為分隔符
        >>>';'.join(['i','love','you'])
        i;love;you
        >>>''.join(['i','love','you'])
        iloveyou
        >>>b= ','
        >>>a=b.join(['i','love','you'])
        >>>print(a)
        i,love,you
        
      • split講字符串分割為幾個子字符串,參數(shù)為分隔符,返回結果存在一個list里
        >>>'i like play football'.split(' ') # 以空格作為分隔符
        ['i', 'like', 'play', 'football']
        
      • replace 替換字符串里面指定的子字符串
        >>>a = 'Tom is a dog. Snoopy is a dog'
        >>>b = a.replace('dog','pig')
        >>>print(a)
        >>>print(b)
        Tom is a dog. Snoopy is a dog
        Tom is a pig. Snoopy is a pig
        
  • 格式化

    • % 數(shù)字代表長度,正數(shù)是右對齊,負數(shù)是左對齊
      >>>vs = [('hasen1',89898),('hasen1112',4444)]
      >>>fs = '''
      >>>%-10s salary: %10d $
      >>>%-10s salary: %10d $
      >>>'''
      >>>print(fs % (vs[0][0],vs[0][1],vs[1][0],vs[1][1]))
      hasen1     salary:      89898 $
      hasen1112  salary:       4444 $  
      
    • format
      • 基本格式
      >>>print('{}'.format(56))
      >>>print('{:10}'.format(56)) # 右對齊
      >>>print('{:<10}'.format(56)) # 左對齊
      >>>print('{:010}'.format(56)) #補0
      56
              56
      56        
      0000000056
      
      • 如果字符串內(nèi)本身含有{},則需要用兩個
      >>>print('{} 他說{{你好}}'.format(123.222))
      123.222 他說{你好}
      
      • 簡易格式(python 3.6以后)
      >>>name = 'hasen'
      >>>print(f'he said his name is {name}')
      he said his name is hasen
      
      >>>print(f'{123.444:.2f}')
      123.44
      
  • which python(which python3) 查詢python的path

  • tell 當前指針位置
    >>>fh = open('abc.txt')
    >>>fh.tell()
    0
    
  • seek 移動指針
    >>>fh = open('abc.txt')
    >>>fh.tell()
    0
    >>>fh.seek(2) #向后移動兩個位置
    >>>fh.tell()
    2
    >>>fh.seek(2,0) #0-從開始位置向后移動兩個位置
    >>>fh.tell()
    2
    >>>fh.seek(2,1) #1-從當前位置向后移動兩個位置
    >>>fh.tell()
    4
    >>>fh.seek(-2,2) #2-從結束位置向前移動兩位
    >>>fh.tell()
    
  • 字典(dict)

    • get方法:如果查不到則返歸指定的值
    >>>dict2 =  {'name':'jack','age':40}
    >>>dict2['age']
    40
    >>>dict2.get('age1',10)
    10
    
    • 取字典里的值
    for name in dict #取出key
    for name,info in dict.items() #取出key和value
    for keys in dict.keys() #取出key
    for values in dict.values()#取出value
    
    • 清空字典
    dict.clear()# 清除內(nèi)容
    dict = {} # 定義為一個新的字典,如果是在其他處調(diào)用,則原dict不變
    
    • 增加另一個dict的內(nèi)容
    >>>d = {1:1,2:2,3:3}
    >>>d
    {1: 1, 2: 2, 3: 3}
    >>>d.update({4:4,5:5})
    >>>d
    {1: 1, 2: 2, 3: 3, 4: 4, 5: 5}
    
  • pip使用

    • 安裝 pip install xxx
    • 卸載 pip uninstall xxx
    • 更新 pip install xxx -u
  • 函數(shù)注釋

    def count(info):
        '''
        :param info: 格式:'姓名1,:age1,姓名2:age2,...'
        :type info:str
        :return: (maxNumAge, maxNum)
        :rtype:list
        計算字符串內(nèi)哪個年齡的人數(shù)最多,并返回人數(shù)最多的年齡和該年齡的人數(shù)
        '''
        pass
    a = 'hasen1 :13,tom mark : 33,hasen3:13,hasen4:13,hasen5:33,   hasen5:40'
    count(a)
    
    
    • :param a -->指明參數(shù)為a
    • :type a:int -->指明參數(shù)a的類型為int
    • :return:a*2 -->指明返回的內(nèi)容
    • :rtype:int -->指明返回的類型
    • 調(diào)用函數(shù)時,按住ctrl,鼠標指向調(diào)用參數(shù)的位置可以查看該函數(shù)的參數(shù)個數(shù)、類型,以及返回類型
    顯示內(nèi)容如下:
    ---def count(info)
    ---inferred type:(info:str) -> list
    
  • 調(diào)試
    • 方法一:IDE debug

      常用于開發(fā)環(huán)境中:
      方便、快捷;
      查看變量、表達式的值

      1. 設置斷點
      2. 執(zhí)行:Debug 'xx'(執(zhí)行到第一個斷點前面的語句為止(斷點處語句還未執(zhí)行到))
      3. 繼續(xù)執(zhí)行
        • Resume Program(F9)繼續(xù)執(zhí)行(執(zhí)行到下一個斷點前)
        • Step Over(F8)單步執(zhí)行(不進入循環(huán)體,每次執(zhí)行完本行)
        • Step Into(F7)單步執(zhí)行(進入循環(huán)體)
        • Step Into My Code(Alt+Shift+F7)單步執(zhí)行(進入循環(huán)體,僅進入我的代碼)
        • Step Over(Shift+F8)單步執(zhí)行(如果已進入循環(huán)體內(nèi),按此按鈕可提前執(zhí)行完循環(huán)并跳出循環(huán)體)
        • Stop 'xxx'(Ctrl+F2)結束debug
    • 方法二:打印信息(pprint)(日志信息)

      常用在沒有IDE的時候:臨時任務;生產(chǎn)環(huán)境(bug不方便重現(xiàn);用log方法,tail/tailf查看日志文件)

      # pprint 支持打印列表和字典
      >>>from pprint import pprint
      >>>a = [1,2,3,4,6]
      >>>pprint(a)
      
      
  • 判斷數(shù)據(jù)類型
    • type 查詢類型
    • isinstance(a,b) 判斷類型(推薦使用)a是否為b類型,返回bool型(True or False)
    >>>type(3)
    <class 'int'>
    >>>isintance(3,int)
    True
    >>>isintance(3,str)
    False
    
  • 條件判斷
    • 三元操作符

      語法:x if 條件 else y -->如果條件為真則結果為x 否則為y

      >>>a,b = 3,4
      >>>small = a if a<b else b
      >>>print(small)
      3
      
    • 斷言(assert)

      當此關鍵字后面的條件為假時,程序自動崩潰并拋出AssertionError的異常

      一般來說我們可以用Ta在程序中植入檢查點,當需要確保程序中的某個條件一定為真才能讓程序正常工作的話,assert關鍵字就非常有用了。

      語法格式:assert 表達式 [, 參數(shù)]

      >>>assert 3>4
      AssertionError
      
      >>>assert 5<4,'XX'
      Traceback (most recent call last):
      File "lhytest.py", line 2, in <module>
          assert 5<4,'XX'
      AssertionError: XX
      
      
  • 連接mysql數(shù)據(jù)庫
    import pymysql.cursors
    
    connect = pymysql.Connect(
        host='199.09.09.99',
        port =3306,
        user='root',
        password='root',
        database='healthywalk'
    )
    cursor = connect.cursor()
    cursor.execute('select answers from questionnaire ')
    value= cursor.fetchall()
    print(value)
    
  • 調(diào)用默認瀏覽器打開某個網(wǎng)址
    import webbrowser
    webbrowser.open('http://www.baidu.com')
    
最后編輯于
?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

  • 初識python基本數(shù)據(jù)類型 數(shù)字 int(整型) long(長整型) -- python3 中已經(jīng)將類型取消 f...
    _阿聰閱讀 486評論 0 1
  • 基本數(shù)據(jù)類型: 1: info = 'abc' info[2] = 'd' 結果是什么,為什么會報錯呢? 答:...
    玖月初識閱讀 4,055評論 5 5
  • Python3筆記 | 第二課:循環(huán)、字符串、列表 程序三大執(zhí)行流程 while循環(huán) while 判斷條件 :條件...
    DoubleProgram閱讀 1,195評論 0 0
  • 今天是我們的表演,我期待了好久的表演,吃過早飯媽媽就帶來到電視臺,過了一會我找到了老師,開始集合了,老師帶我們來到...
    李枝焰閱讀 431評論 0 0
  • “如果你說的都是真的,那你跟我回去吧?!辫F竹軒說著就去翻找他穿越來時手里拿著的那奇怪隕石。 可是那隕石早在我又一次...
    沐弘晨閱讀 327評論 0 24

友情鏈接更多精彩內(nèi)容