數字、字元串、列表

来源:https://www.cnblogs.com/chenwang-23/archive/2019/04/05/10659707.html
-Advertisement-
Play Games

一、可變與不可變類型 二、數字類型 1、用途 2、定義方式 3、總結 三、字元串類型 1、作用 2、定義方式 3、常用操作+內置方法 # 優先掌握的操作: 4、總結 四、列表類型 1、用途 2、定義方式 3、常用操作+內置的方法 4、總結 ...


一、可變與不可變類型

1、可變類型:值改變,但是id不變,證明就是在改變原值,是可變類型。
2、不可變類型:值改變,但是id也跟著變,證明是產生了新的值(也意味著創建了新的記憶體空間),是不可變類型

# 總結:
可變類型:列表,字典
不可變類型:整型,浮點型,字元串,元組

二、數字類型

1、用途

整型:記錄年齡、等級等
浮點型:記錄薪資、身高、體重等

2、定義方式

整型:a = 3  #a = int(3)
數據類型轉換:只能將純數字的字元串轉成int

浮點型:salary = 10.3  #salary = float(10.3)
數據類型轉換:只能將包含小數的字元串轉成float

3、總結

存一個值
不可變類型

三、字元串類型

1、作用

記錄描述性質的狀態

2、定義方式

在單引號、雙引號、三引號內包含一串字元串
msg = 'hello'  #msg = str('hello)
數據類型轉換:所有類型都可以被str轉成字元串類型

3、常用操作+內置方法

# 優先掌握的操作:

1、按索引取值(正向取+反向取):只能取且取出來的字元仍然是字元串類型
msg = 'hello'
print(msg[0],type(msg[0]))  #h <class 'str'>
print(msg[-1])  #o
msg[0] = 'H'  #error 只能取

2、切片(顧頭不顧尾,步長)
msg = 'hello world'
res = msg[0:3:1]  #0 1 2
print(res)  #h e l
print(msg)  #原值並不改變
res = msg[:]  #0 1 2 3 4 5 6 7 8 9 10
res = msg[::2]  #0 2 4 6 8 10
res = msg[-1:-12:-1]  #10 9 8 ... 0
res = msg[-1::-1]  #一直執行到最後
res = msg[::-1]  #預設從後向前依次出發

3、長度 len
print(len(msg))

4、成員運算 in not in:判斷一個子字元串是否存在於大字元串中,返回的值是 True False
msg = 'hello'
print('hel' in msg) #True
print('hell' not in msg) #False
print(not 'hel' in msg) #False

5、移除空白strip:用來去除字元串左右兩邊的字元,不指定預設去除的是空格
msg = '   he llo   '
res = msg.strip() #he llo 無法去除中間的空格
print('*****eg**on****'.strip('*')) #eg**on
print('***%%%$eg*on&&**#'.strip('*%$&#')) #eg*on
print('*****egon******'.lstrip('*')) #egon******
print('*****egon******'.rstrip('*')) #*****egon
#下麵一個程式主要是針對於用戶在輸入信息時會輸入空格
name=input('username>>>: ').strip() # name='egon     '
pwd=input('password>>>: ').strip()
if name == 'egon' and pwd == '123':
    print('login successful')
else:
    print('輸錯了。。。')
       
6、切分split:針對有規律的字元串,按照某種分隔符切成列表
info='egon:18:male'
res=info.split(':')
print(res,type(res))  #['egon','18','male'] <class 'list'>
print(res[0],res[1])  #egon 18

cmd='get|a.txt|33333'
print(cmd.split('|',1))  #['get','a.txt|33333']
cmd='get|a.txt|33333'
print(cmd.split('|',2))  #['get','a.txt','33333']

用:號作連接符號將純字元串的列表拼接成一個字元串
l=['egon', '18', 'male']  
res=l[0]+':'+l[1]+':'+l[2]
print(res) # 'egon:18:male'
res=','.join(l)
print(res) # 'egon,18,male'
res = ':'.join(l)
print(res) # 'egon:18:male'

7、迴圈
for item in 'hello':
   print(item)

需要掌握的操作
1、strip,lstrip,rstrip
print('******egon***********'.strip('*')) #egon
print('******egon***********'.lstrip('*')) #egon**********
print('******egon***********'.rstrip('*')) #******egon

2、lower,upper
print('Abc123'.lower()) #abc123
print('Abc123'.upper()) #ABC123

3、startswith,endswith
msg='alex is dsb'
print(msg.startswith('alex i'))
print(msg.endswith('dsb'))

4、format的三種玩法
res='my name is %s my age is %s' %('egon',18)
print(res) #my name is egon my age is 18

res='my name is {name} my age is {age}'.format(age=18,name='egon')
print(res) #my name is egon my age is 18

瞭解
res='my name is {} my age is {}'.format('egon',18)
print(res) #my name is egon my age is 18
res='my name is {0}{1} my age is {1}{2}{1}{3}'.format('egon',18,'chen',20)
print(res) #my name is egon18 my age is 18chen1820

5、split,rsplit
msg='a:b:c:d'
print(msg.split('b',1)) #['a:',':c:d']
print(msg.rsplit(':',2)) #['a:b','c','d']
print(msg.rsplit(':')) #['a','b','c','d']

6、replace
msg='kevin is kevin is hahahah'
res=msg.replace('kevin','sb',1)
print(res) #sb is kevin is hahaha

7、isdigit
#判斷字元串是否是純數字
print('123123'.isdigit()) # 如果字元串是由純數字組成的,則返回True
print('123123   '.isdigit())
print('123123asdf'.isdigit())
print('12312.3'.isdigit())

score=input('>>>>: ').strip() #score='asdfasdfasfd'
if score.isdigit():
   score=int(score)
   if score >= 90:
       print('優秀')
   else:
       print('小垃圾')
else:
   print('必須輸入純數字')

瞭解的操作
1、find,rfind,index,rindex,count
print('123 ke123ke'.find('ke')) #4
print('123 ke123ke'.rfind('ke')) #9
print('123 ke123ke'.index('ke')) #4
print('123 ke123ke'.rindex('ke')) #4

print('123 ke123ke'.find('xxxx')) #-1
print('123 ke123ke'.index('xxxx')) #ValueError
print('123 ke123ke'.count('ke')) #2
print('123 ke123ke'.count('ke',0,5)) #0 因為只能取到0到4(顧頭不顧尾)
print('123 ke123ke'.count('ke',0,6)) #1
print('123 ke123ke'.count('ke',0,15)) #2

2、center,ljust,rjust,zfill
print('egon'.center(50,'*')) # ****************egon******************
print('egon'.ljust(50,'*')) # egon**********************************
print('egon'.rjust(50,'*')) # **********************************egon

print('egon'.rjust(50,'0'))
print('egon'.zfill(50))  #z:表示zero   zfill:表示用0來填充

3、captalize,swapcase,title
print('abcdef dddddd'.capitalize())  #僅僅把字元串中第一個字母轉換為大寫,如果本來就為大寫,則還是大寫
print('Abcdef dddddd'.capitalize())
print('abcAef dddddd'.swapcase()) #大小寫反轉
print('abcAef dddddd'.title())   #每個單詞開頭都轉換為大寫
print('abcAef Dddddd'.title())

4、is數字系列
num1=b'4' #bytes
num2='4' #unicode,python3中無需加u就是unicode
num3='四' #中文數字
num4='Ⅳ' #羅馬數字

bytes與阿拉伯數字組成的字元串
print(num1.isdigit())
print(num2.isdigit())
print(num3.isdigit())
print(num4.isdigit())

阿拉伯數字組成的字元串
print(num2.isdecimal())
print(num3.isdecimal())
print(num4.isdecimal())

阿拉伯數字\中文\羅馬組成的字元串
print(num2.isnumeric())
print(num3.isnumeric())
print(num4.isnumeric())

5、is其他

4、總結

存一個值

有序

不可變

四、列表類型

1、用途

按照位置記錄多個值,索引對應值

2、定義方式

在[]內用逗號分隔開多個任意類型的值
l=['a',11,11.3,] # l=list(['a',11,11.3,])

數據類型轉換:但凡能夠被for迴圈遍歷的數據類型都可以傳給list,被其轉換成列表
res=list('hello')
# res=list(123)
print(res)

res=list({'a':1,'b':2,'c':3}) # []
print(res) #['a','b','c']

3、常用操作+內置的方法

#優先掌握的操作:
3.1、按索引存取值(正向存取+反向存取):即可存也可以取
l=['a','b','c','d','e']
print(l[0])
print(l[-1])
print(id(l))
l[0]='A'
print(id(l))

#強調強調強調!!!:對於不存在的索引會報錯
l[5]='AAAA'  #error
但是對於字典來說卻可以添加索引
dic={"k1":111}
dic['k2']=2222
print(dic) #{'k1':111,'k2':2222}

3.2、切片(顧頭不顧尾,步長)
l=['a','b','c','d','e']
print(l[1:4])  #['b','c','d']
print(l[::-1])  #['e','d','c','b','a']

3.3、長度
l=['a','b','c','d','e']
print(len(l)) #5

3.4、成員運算in和not in
l=['a','b','c','d','e']
print('a' in l) #True

3.5、追加與insert
l=['a','b','c','d','e']
l.append('xxx')
l.append('yyy')
print(l)

l.insert(0,'xxxx')
print(l)  #['xxxx','a','b','c','d','e']

3.6、刪除
l=['a','bbb','c','d','e']
del是一種通用的刪除操作,沒有返回值
del l[0]
print(l)  #['bbb','c','d','e']

dic={'k1':1}
del dic['k1']
print(dic)  #{}

l.remove(指定要刪除的那個元素),沒有返回值
res=l.remove('bbb')  
l.remove('bbb')
print(l) #['a','c','d','e']
print(res) #None

l.pop(指定要刪除的那個元素的索引),返回剛剛刪掉的那個元素
l=['a','bbb','c','d','e']
l.pop(-1)
res=l.pop(1)
print(l) #['a','bbb','c','d']
print(res) #e

3.7、迴圈
l=['a','b','c','d','e']
for item in l:
   print(item)

練習:
隊列:先進先出
l=[]
# 入隊
l.append('first')
l.append('second')
l.append('third')
print(l)
# 出隊
print(l.pop(0))
print(l.pop(0))
print(l.pop(0))

堆棧:後進先出

需要掌握的操作
l=['aaa','bb',345]
l.clear()
l.append([1,2,3])
l.append('abc')
l.append(5)
print(l)
l = []
for i in [1,2,3]:
   l.append(i)
print(l)
l.extend('123')
print(l)
l.extend('abc')
print(l)
l.extend(['g','e','f'])  #本質就是for迴圈,所以後面跟上列表或者字元串是一樣的
print(l)

# 將列表反轉
l = ['a','b'.'c']
l.reverse()
print (l)  #['c','b','a']

# 只有在類中中所有元素都是同種類型的情況下才能用sort排序
l=[1,3,2]
l.sort(reverse=True)
print(l)  #[3,2,1]

l=['z','d','a']
l.sort()
print(l) #['a','b','z']

4、總結

存多個值

有序

可變

 


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • XML的解析簡介: 在學習JavaScript時,我們用的DOM來解析HEML文檔,根據HTML的層級結構在記憶體中分配一個樹形結構,把HTML的標簽啊,屬性啊和文本之類的都封裝成對象。 比如:document對象,element對象,屬性對象,文本對象,Node結點對象 我們通常有兩種方式來解析XM ...
  • (1) plot是標準的繪圖庫,調用函數plot(x,y)就可以創建一個帶有繪圖的圖形視窗(其中y是x的函數)。輸入的參數為具有相同長度的數組(或列表);或者plot(y)是plot(range(len(y)),y)的簡寫。 例1:python實現使用200個採樣點來繪製sin(x),並且每隔四個點 ...
  • 一、元組tuple 1、作用 存多個值,對比列表來說,元組不可變,主要是用來讀。 2、定義 與列表類型比,只不過[ ]換成() 3、常用操作 4、元組案列 二、字典dict 特別瞭解:dict是python中僅存的mapping類型 1、作用 存多個值,key-value存取,取值速度快。 2、定義 ...
  • 一,本機配置 Win10 64bit NVIDIA GeForce GTX 960M Python3.7(Anaconda) 二,安裝CUDA 親測,TensorFlow-gpu1.13.1支持cuda10.0的版本,所以我們可直接選擇cuda10.0的版本 Window10下載CUDA10 安裝步 ...
  • PHP原生寫的生成圖片縮略圖類,本文以京東商品圖片為例,分別生成三種不同尺寸的圖片。調用方法很簡單隻要傳參數高度和寬度,及新圖片的名稱。 引入縮略圖類 生成三個不同尺寸縮略圖 本實例下載:https://www.sucaihuo.com/php/867.html ...
  • John and Mary want to travel between a few towns A, B, C ... Mary has on a sheet of paper a list of distances between these towns. ls = [50, 55, 57, 5 ...
  • 1.變數的作用域和靜態變數 函數的參數以及參數的引用傳遞 函數的返回值以及引用返回 外部文件的導入 系統內置函數的考察 變數的作用域也稱為變數的範圍,變數的範圍即他定義上下文的背景(也是它生效的範圍)。大部分php變數只有一生效的範圍,這個單獨的範圍也包括include 和require 引入的文件 ...
  • 矩陣快速冪 設答案為f(i) 舉個例子: 當i==2時,包含0的值有:10,20,30,40,50,60,70,80,90,100;0的個數為11,f(2)=11; i==3時;可以從i==2的情況遞推, 第一步:i==2時的數據範圍:1-100;在這100個數後面補0;補0後,這些數在1-1000 ...
一周排行
    -Advertisement-
    Play Games
  • 前言 本文介紹一款使用 C# 與 WPF 開發的音頻播放器,其界面簡潔大方,操作體驗流暢。該播放器支持多種音頻格式(如 MP4、WMA、OGG、FLAC 等),並具備標記、實時歌詞顯示等功能。 另外,還支持換膚及多語言(中英文)切換。核心音頻處理採用 FFmpeg 組件,獲得了廣泛認可,目前 Git ...
  • OAuth2.0授權驗證-gitee授權碼模式 本文主要介紹如何筆者自己是如何使用gitee提供的OAuth2.0協議完成授權驗證並登錄到自己的系統,完整模式如圖 1、創建應用 打開gitee個人中心->第三方應用->創建應用 創建應用後在我的應用界面,查看已創建應用的Client ID和Clien ...
  • 解決了這個問題:《winForm下,fastReport.net 從.net framework 升級到.net5遇到的錯誤“Operation is not supported on this platform.”》 本文內容轉載自:https://www.fcnsoft.com/Home/Sho ...
  • 國內文章 WPF 從裸 Win 32 的 WM_Pointer 消息獲取觸摸點繪製筆跡 https://www.cnblogs.com/lindexi/p/18390983 本文將告訴大家如何在 WPF 裡面,接收裸 Win 32 的 WM_Pointer 消息,從消息裡面獲取觸摸點信息,使用觸摸點 ...
  • 前言 給大家推薦一個專為新零售快消行業打造了一套高效的進銷存管理系統。 系統不僅具備強大的庫存管理功能,還集成了高性能的輕量級 POS 解決方案,確保頁面載入速度極快,提供良好的用戶體驗。 項目介紹 Dorisoy.POS 是一款基於 .NET 7 和 Angular 4 開發的新零售快消進銷存管理 ...
  • ABP CLI常用的代碼分享 一、確保環境配置正確 安裝.NET CLI: ABP CLI是基於.NET Core或.NET 5/6/7等更高版本構建的,因此首先需要在你的開發環境中安裝.NET CLI。這可以通過訪問Microsoft官網下載並安裝相應版本的.NET SDK來實現。 安裝ABP ...
  • 問題 問題是這樣的:第三方的webapi,需要先調用登陸介面獲取Cookie,訪問其它介面時攜帶Cookie信息。 但使用HttpClient類調用登陸介面,返回的Headers中沒有找到Cookie信息。 分析 首先,使用Postman測試該登陸介面,正常返回Cookie信息,說明是HttpCli ...
  • 國內文章 關於.NET在中國為什麼工資低的分析 https://www.cnblogs.com/thinkingmore/p/18406244 .NET在中國開發者的薪資偏低,主要因市場需求、技術棧選擇和企業文化等因素所致。歷史上,.NET曾因微軟的閉源策略發展受限,儘管後來推出了跨平臺的.NET ...
  • 在WPF開發應用中,動畫不僅可以引起用戶的註意與興趣,而且還使軟體更加便於使用。前面幾篇文章講解了畫筆(Brush),形狀(Shape),幾何圖形(Geometry),變換(Transform)等相關內容,今天繼續講解動畫相關內容和知識點,僅供學習分享使用,如有不足之處,還請指正。 ...
  • 什麼是委托? 委托可以說是把一個方法代入另一個方法執行,相當於指向函數的指針;事件就相當於保存委托的數組; 1.實例化委托的方式: 方式1:通過new創建實例: public delegate void ShowDelegate(); 或者 public delegate string ShowDe ...