py基礎語法簡述

py基礎,常用sdk

一些要點

  1. python中是沒有常量的關鍵字的,只是我們常常約定使用大寫字符組合的變量名表示常量,也有“不要對其進行賦值”的提醒操作
PI = 3.14
  1. python3中有六個標準的數據類型: Number(數字)、String(字符串)、Boolean(布爾)、List(列表)、Tuple(元組)、Sets(集合)、Dictionary(字典)
    不可變數據(4個): Number(數字)、String(字符串)、Tuple(元組)、Boolean(布爾)
    可變數據(3個): List(列表)、Dictionary(字典)、Sets(集合)
    python3支持三種不同的數值類型: 整型(int)、浮點型(float)、復數(complex)

字符串

lstrip、rstrip、strip、replace、find、ljust、rjust、isalpha、isdigit

text = '     abcdef125s  wr2258abcd      '
# 刪掉開頭和結尾的空格
print('original:', text) 
print('  lstrip:', text.lstrip(' ')) 
print('  rstrip:', text.rstrip(' '))
print('   strip:', text.strip(' '))
print(' replace:', text.replace('a', 'A'))
print(' replace:', text.replace('a', 'A', 1))
print('    find:', text.find('a'))
# 填充字符***
print('text.ljust(50, \'*\') :', text.ljust(50, '*'))
print('text.rjust(50, \'*\') :', text.rjust(50, '*'))
print('text.center(50, \'*\') :', text.center(50, '*'))
# 判斷是否全是字母/數字
print('isalpha:', 'abc -', 'abc'.isalpha(), '123 -', '123'.isalpha(), 'a12 -', 'a12'.isalpha())
print('isdigit:', 'abc -', 'abc'.isdigit(), '123 -', '123'.isdigit(), 'a12 -', 'a12'.isdigit())

輸出:

original:      abcdef125s  wr2258abcd      lstrip: abcdef125s  wr2258abcd      rstrip:      abcdef125s  wr2258abcdstrip: abcdef125s  wr2258abcdreplace:      Abcdef125s  wr2258Abcd      replace:      Abcdef125s  wr2258abcd      find: 5
text.ljust(50, '*') :      abcdef125s  wr2258abcd      *****************
text.rjust(50, '*') : *****************     abcdef125s  wr2258abcd      
text.center(50, '*') : ********     abcdef125s  wr2258abcd      *********
isalpha: abc - True 123 - False a12 - False
isdigit: abc - False 123 - True a12 - False

split和join

text2 = 'a,d,dw,d,s,w,t,c,w,'
list1 = text2.split(',')print('text2:', text2)
print('list1:', list1)
print('join:', ','.join(list1))

輸出

text2: a,d,dw,d,s,w,t,c,w,
list1: ['a', 'd', 'dw', 'd', 's', 'w', 't', 'c', 'w', '']
join: a,d,dw,d,s,w,t,c,w,

startswith和endswith

text3 = 'Hello world'
print('start with world:', text3.startswith('world'))
print('start with Hello:', text3.startswith('Hello'))
print('start with world:', text3.endswith('world'))
print('start with Hello:', text3.endswith('Hello'))

輸出

start with world: False
start with Hello: True
start with world: True
start with Hello: False

空字符串表示否
空對象會輸出None

text4 = ''
print(not text4) # 用于條件時,0、0.0、空字符串被認為是False
print(text4 == '')sample
print(sample) # 對象為空會定義為None```
輸出
True
True
None

list

list按index取值,: 用法,list * 2,list合并

list_1 = [1, 2, 3]
print('list_1 :'.rjust(11), list_1)
list_1.append(4)
print('append(4) :'.rjust(11), list_1)
print('[:1] :'.rjust(11), list_1[1:])
print('[:2] :'.rjust(11), list_1[:2])
print('[-1] :'.rjust(11), list_1[-1])
print('[:] :'.rjust(11), list_1[:])
print()list_2 = [5, 6, 7]
list_merge = list_1 + list_2
print('list_2 :', list_2)
print('list_2 * 2 :', list_2 * 2)
print('list_1 + list_2 :', list_merge)

輸出

   list_1 : [1, 2, 3]
append(4) : [1, 2, 3, 4][:1] : [2, 3, 4][:2] : [1, 2][-1] : 4[:] : [1, 2, 3, 4]list_2 : [5, 6, 7]
list_2 * 2 : [5, 6, 7, 5, 6, 7]
list_1 + list_2 : [1, 2, 3, 4, 5, 6, 7]

list遍歷,list按index取值,list插入,list移除,list隨機排序,list排序,list判空

import randommy_list = [10, 20, 30]
print('my_list :', my_list)print('my_list 遍歷 :')
for item in my_list:print(item)a, b, c = my_list
print('a, b, c = my_list, a, b, c = ', a, b, c)print('my_list.index(20) :', my_list.index(20))my_list.insert(1, 15)
print('my_list.insert(1, 15) :', my_list)my_list.remove(20)
print('my_list.remove(20) :', my_list)random.shuffle(my_list)
print('random.shuffle(my_list) :', my_list)my_list.sort()
print('my_list.sort() :', my_list)my_list = []
print('my_list = [] :', my_list)if not my_list:print('if not my_list :', 'my_list is empty')
else:print('if not my_list :', 'my_list is not empty')

輸出

my_list : [10, 20, 30]
my_list 遍歷 :
10
20
30
a, b, c = my_list, a, b, c =  10 20 30
my_list.index(20) : 1
my_list.insert(1, 15) : [10, 15, 20, 30]
my_list.remove(20) : [10, 15, 30]
random.shuffle(my_list) : [10, 30, 15]
my_list.sort() : [10, 15, 30]
my_list = [] : []
if not my_list : my_list is empty

list深拷貝

list_deep_copy  = list_2[:]
list_2[1] = 2
print(list_2)
print(list_deep_copy)

輸出

[5, 2, 7]
[5, 6, 7]

set

set創建,set遍歷,set排序,set插入,discard嘗試移除,pop操作,判斷set存在,set清空

s0 = set()
s1 = set(list_1)
s2 = set({1, '2'})print('s0 = set(), s0 :', s0)
print('s1 = set(list_1), s1 :', s1)
print('s2 = set({1, \'2\'}), s2 :', s2, '\n')print('遍歷 s2 :')
for item in s2:print(item, type(item))
print('\n')s2.add(3)
s2.add(4)
s2.add(5)
print('s2.add(3), s2.add(4), s2.add(5), s2 :', s2, '\n')s2.discard(3)
print('s2.discard(3), s2 :', s2, '\n')print('len(s2) :', len(s2), '\n')print('s2.pop() :', s2.pop())
print('s2 :', s2, '\n')if 4 in s2:print('if 4 in s2 :', '4 in s2')
print('\n')s2.clear()
print('s2.clear(), s2 :', s2, '\n')

輸出

s0 = set(), s0 : set()
s1 = set(list_1), s1 : {1, 2, 3, 4}
s2 = set({1, '2'}), s2 : {1, '2'} 遍歷 s2 :
1 <class 'int'>
2 <class 'str'>s2.add(3), s2.add(4), s2.add(5), s2 : {1, '2', 3, 4, 5} s2.discard(3), s2 : {1, '2', 4, 5} len(s2) : 4 s2.pop() : 1
s2 : {'2', 4, 5} if 4 in s2 : 4 in s2s2.clear(), s2 : set() 

tuple

tuple創建,tuple元素計數,tuple查找index

tuple1 = (1, 1, 3, 4, 5)
print(type(tuple1), '\n')for item in tuple1:print(item)
print('\n')print(tuple1.count(1))
print(tuple1.index(5))

輸出

<class 'tuple'> 1
1
3
4
52
4

dict

dict創建,dict取值,dict插入,嵌套dict,打印多層dict,dict設置默認值

my_dict = {'name': '張三', 'age': 18}
print(my_dict)
print(my_dict['name'])
my_dict['city'] = '北京'
print(my_dict)
print('\n')print('name' in my_dict)
print('sex' in my_dict)
print('age' not in my_dict)
print('\n')print(my_dict.setdefault('hobby', 'football'))
print(my_dict.setdefault('hobby', 'basketball'))
print('\n')from pprint import pprintdict = {'my_dict': my_dict, 'list_merge': list_merge, 's2': s2}
pprint(dict, indent=2)
print('\n')

輸出

{'name': '張三', 'age': 18}
張三
{'name': '張三', 'age': 18, 'city': '北京'}True
False
Falsefootball
football{ 'list_merge': [1, 2, 3, 4, 5, 6, 7],'my_dict': {'age': 18, 'city': '北京', 'hobby': 'football', 'name': '張三'},'s2': set()}

if、while、for

if判斷,while循環,for循環,雙層for循環

name = '1'
if name == 'Alice':print('Hi, I\'m Alice')
elif name == 'Bob':print('Hi, I\'m Bob')
else:print('Hi, I\'m', name)
print('\n')cnt = 3
while cnt > 0:print('cnt =', cnt)cnt -= 1
print('\n')for i in range(3):print('i =', i)
print('\n')tmp1 = [1,3,5,7,9]
tmp2 = [2,4,6,8,10]
tmp_list = [tmp1, tmp2]print(tmp_list)num_set = set(num for tmp in tmp_list for num in tmp)
print(num_set)

輸出

Hi, I'm 1cnt = 3
cnt = 2
cnt = 1i = 0
i = 1
i = 2[[1, 3, 5, 7, 9], [2, 4, 6, 8, 10]]
{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}

exception

def sample(divideBy):try:return 42/divideByexcept ZeroDivisionError:print('error:invalid arguments')print(sample(2)) # 輸出21.0
print(sample(0)) # 打印錯except信息,并輸出None

輸出

21.0
error:invalid arguments
None

參考:
https://zhuanlan.zhihu.com/p/694203031
https://blog.csdn.net/m0_56051805/article/details/126900242

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/web/40883.shtml
繁體地址,請注明出處:http://hk.pswp.cn/web/40883.shtml
英文地址,請注明出處:http://en.pswp.cn/web/40883.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

基于Python爬蟲的城市二手房數據分析可視化

基于Python爬蟲的城市二手房數據分析可視化 一、前言二、數據采集(爬蟲,附完整代碼)三、數據可視化(附完整代碼)3.1 房源面積-總價散點圖3.2 各行政區均價3.3 均價最高的10個小區3.4 均價最高的10個地段3.5 戶型分布3.6 詞云圖四、如何更換城市一、前言 二手房具有價格普…

CSS position屬性之relative和absolute

目錄 1 參考文章2 五個屬性值3 position:static4 position:relative&#xff08;相對&#xff09;5 position:absolute&#xff08;絕對&#xff09; 1 參考文章 https://blog.csdn.net/lalala_dxf/article/details/123566909 https://blog.csdn.net/WangMinGirl/article/deta…

最靈活且易用的C++開源串口通信調試軟件

這款C開源串口調試軟件&#xff0c;集成了豐富的功能&#xff0c;為用戶提供高效、便捷的串口通信調試體驗。以下是其核心功能亮點&#xff1a; 基礎功能&#xff1a; 數據交互自如&#xff1a;支持串口數據的輕松讀取與發送&#xff0c;讓數據交換變得簡單直接。 靈活配置參…

基于順序表的通訊錄實現

一、前言 基于已經學過的順序表&#xff0c;可以實現一個簡單的通訊錄。 二、通訊錄相關頭文件 //Contact.h #pragma once#define NAME_MAX 20 #define TEL_MAX 20 #define ADDR_MAX 20 #define GENDER_MAX 20typedef struct PersonInfo {char name[NAME_MAX];char gender[G…

Python的招聘數據分析與可視化管理系統-計算機畢業設計源碼55218

摘要 隨著互聯網的迅速發展&#xff0c;招聘數據在規模和復雜性上呈現爆炸式增長&#xff0c;對數據的深入分析和有效可視化成為招聘決策和招聘管理的重要手段。本論文旨在構建一個基于Python的招聘數據分析與可視化管理系統。 該平臺以主流招聘平臺為數據源&#xff0c;利用Py…

MSPM0G3507——解決printf重定向在其他位置不能用的問題(printf重定向的補充)

除了之前發的文章的printf重定向的代碼之外&#xff0c;還要加上這樣一段代碼即可 int puts(const char *_ptr) {int count fputs(_ptr,stdout);count fputs("\n",stdout);return count;} 完整的重定向&#xff1a; int fputc(int c, FILE* stream) {DL_UART_Main_…

昇思25天學習打卡營第2天|MindSpore快速入門

打卡 目錄 打卡 快速入門案例&#xff1a;minist圖像數據識別任務 案例任務說明 流程 1 加載并處理數據集 2 模型網絡構建與定義 3 模型約束定義 4 模型訓練 5 模型保存 6 模型推理 相關參考文檔入門理解 MindSpore數據處理引擎 模型網絡參數初始化 模型優化器 …

一個字符串的全部子序列和全排列

在計算機科學中&#xff0c;字符串的子序列和全排列是兩個重要的概念。 1. 子序列 子序列是從一個序列中刪除一些&#xff08;或不刪除&#xff09;元素而不改變剩余元素的順序形成的新序列。 例如&#xff0c;字符串 “abc” 的子序列包括&#xff1a; “”&#xff08;空…

如何選擇TikTok菲律賓直播網絡?

為了滿足用戶對于實時互動的需求&#xff0c;TikTok推出了直播功能&#xff0c;讓用戶能夠與粉絲即時交流。本文將探討如何選擇適合的TikTok菲律賓直播網絡&#xff0c;并分析OgLive是否是值得信賴的選擇。 TikTok菲律賓直播網絡面臨的挑戰 作為全球領先的短視頻平臺&#xff…

Python + OpenCV 開啟圖片、寫入儲存圖片

這篇教學會介紹OpenCV 里imread()、imshow()、waitKey() 方法&#xff0c;透過這些方法&#xff0c;在電腦中使用不同的色彩模式開啟圖片并顯示圖片。 imread() 開啟圖片 使用imread() 方法&#xff0c;可以開啟圖片&#xff0c;imread() 有兩個參數&#xff0c;第一個參數為檔…

Google Play上架:惡意軟件、移動垃圾軟件和行為透明度詳細解析和解決辦法 (一)

近期整理了許多開發者的拒審郵件和內容,也發現了許多問題,今天來說一下關于惡意軟件這類拒審的問題。 目標郵件如下: 首先說一下各位小伙伴留言私信的一個方法,提供你的拒審郵件和時間,盡可能的詳細,這樣會幫助我們的團隊了解你們的問題,去幫助小伙伴么解決問題。由于前…

在 .NET 8 Web API 中實現彈性

在現代 Web 開發中&#xff0c;構建彈性 API 對于確保可靠性和性能至關重要。本文將指導您使用 Microsoft.Extensions.Http.Resilience 庫在 .NET 8 Web API 中實現彈性。我們將介紹如何設置重試策略和超時&#xff0c;以使您的 API 更能抵御瞬時故障。 步驟 1.創建一個新的 .…

集成學習(一)Bagging

前邊學習了&#xff1a;十大集成學習模型&#xff08;簡單版&#xff09;-CSDN博客 Bagging又稱為“裝袋法”&#xff0c;它是所有集成學習方法當中最為著名、最為簡單、也最為有效的操作之一。 在Bagging集成當中&#xff0c;我們并行建立多個弱評估器&#xff08;通常是決策…

排序——數據結構與算法 總結8

目錄 8.1 排序相關概念 8.2 插入排序 8.2.1 直接插入排序&#xff1a; 8.2.2 折半插入排序&#xff1a; 8.2.3 希爾排序&#xff1a; 8.3 交換排序 8.3.1 冒泡排序&#xff1a; 8.3.2 快速排序&#xff1a; 8.4 選擇排序 8.4.1 簡單選擇排序 8.4.2 堆排序 8.5 歸并…

磁盤就是一個超大的Byte數組,操作系統是如何管理的?

磁盤在操作系統的維度看&#xff0c;就是一個“超大的Byte數組”。 那么操作系統是如何對這塊“超大的Byte數組”做管理的呢&#xff1f; 我們知道在邏輯上&#xff0c;上帝說是用“文件”的概念來進行管理的。于是&#xff0c;便有了“文件系統”。那么&#xff0c;文件系統…

當前國內可用的docker加速器搜集 —— 筑夢之路

可用鏡像加速器 以下地址搜集自網絡&#xff0c;僅供參考&#xff0c;請自行驗證。 1、https://docker.m.daocloud.io2、https://dockerpull.com3、https://atomhub.openatom.cn4、https://docker.1panel.live5、https://dockerhub.jobcher.com6、https://hub.rat.dev7、http…

最新版情侶飛行棋dofm,已解鎖高階私密模式,單身狗務必繞道!(附深夜學習資源)

今天阿星要跟大家聊一款讓阿星這個大老爺們兒面紅耳赤的神奇游戲——情侶飛行棋。它的神奇之處就在于專為情侶設計&#xff0c;能讓情侶之間感情迅速升溫&#xff0c;但單身狗們請自覺繞道&#xff0c;不然后果自負哦&#xff01; 打開游戲&#xff0c;界面清新&#xff0c;操…

HTML5使用<progress>進度條、<meter>刻度條

1、<progress>進度條 定義進度信息使用的是 progress 標簽。它表示一個任務的完成進度&#xff0c;這個進度可以是不確定的&#xff0c;只是表示進度正在進行&#xff0c;但是不清楚還有多少工作量沒有完成&#xff0c;也可以用0到某個最大數字&#xff08;如&#xff1…

vs2022安裝qt vs tool

1 緣由 由于工作的需要&#xff0c;要在vs2022上安裝qt插件進行開發。依次安裝qt&#xff0c;vs2022&#xff0c;在vs2022的擴展管理中安裝qt vs tool。 2 遇到困難 問題來了&#xff0c;在qt vs tool的設置qt version中出現問題&#xff0c;設置msvc_64-bit時出現提示“invali…

西安石油大學 課程習題信息管理系統(數據庫課設)

主要技術棧 Java Mysql SpringBoot Tomcat HTML CSS JavaScript 該課設必備環境配置教程&#xff1a;&#xff08;參考給出的鏈接和給出的關鍵鏈接&#xff09; JAVA課設必備環境配置 教程 JDK Tomcat配置 IDEA開發環境配置 項目部署參考視頻 若依框架 鏈接數據庫格式注…