1. 程式人生 > >Python封裝函式之str、list、tuple、dict、set

Python封裝函式之str、list、tuple、dict、set

  • 字元
encode
decode
test = 'aLexaLex'
v = test.find('ex',5,7)    #預設從開始往後找現在設定5到7的閉開區間
print(v)                   #找到第一個之後,獲取其位置,沒找到返回-1


test = '你是風兒我是沙'
print(test)
t = ' '
v = t.join(test)               #將字串中的每一個元素按照指定分隔符進行拼接
print(v)

test = 'aLex'
v1 = test.islower()              #判斷全是小寫
v3 = test.isupper()              #判斷全是大寫
v2 = test.lower() #全是變成小寫 v4= test.upper() #全是變成大寫 print(v1,v2,v3,v4) test = 'testasdsdfgs' v1 = test.rpartition('s') #找到最右邊的字元分割成3份 v2 = test.partition('s') #找到最左邊的字元分割成3份 v3 = test.rsplit('s',2) #找到字元(預設全部,這找2個從右邊開始),去除字元並分割
v4 = test.split('s') #找到字元,去除字元並分割 print(v1,v2,v3,v4) test = '\n1 \naLe xx' v1 = test.lstrip() #去除空白\n\t,從最左邊開始連續的 v2 = test.rstrip() #去除空白\n\t,從最右邊開始連續的 v3 = test.strip() #去除空白\n\t,從2邊開始連續的 v4 = test.rstrip('x') #指定去除x,從2變開始連續的
print(v1,v2,v3,v4)

test = 'aLex'
v = test[0:2]
v = len(test)  #可以讀列表元素
index = 0
while index < len(test):
    index += 1
for index in test:
    print(index)
v = range(0,100,5)   #建立一個100個數的陣列,for迴圈才真實建立,預設0開始,可設定0到100步長5
for item in rang(0,len(test)):
    print(item,test[item])
print('=====================')
test = 'aLex'
v = test.capitalize()   #首字母大寫其他字母小寫
print(v)

test = 'aLex'
v1 = test.casefold()      #將字串中所有語言中大寫變小寫
print(v1)
v2 = test.lower()         #將字串中英文大寫變小寫
print(v2)

test = 'aLex'
v = test.center(20,'*')    #設定寬度,並內容居中,20代指總長度,*空白未知填充,一個字元,可有可無
v1 = test.ljust(20,'*')    #設定寬度,並內容居左,20代指總長度,*空白未知填充,一個字元,可有可無
v2 = test.rjust(20,'*')    #設定寬度,並內容居右,20代指總長度,*空白未知填充,一個字元,可有可無
v3 = test.zfill(20)        #設定寬度,並內容居右,20代指總長度,只用0來填充
print(v,v1,v2,v3)

test = 'aLexaLex'
v = name.count('ex')       #去字串中尋找子序列出現次數
print(v)

test = 'aLexaLex'
v = name.count('ex',6,8)   #數字符出現次數,預設全部,設定從第6個到第8個的閉開區間
print(v)

test = 'aLex'
v = test.endswith('ex')      #判斷以什麼結尾
print(v)
v = test.startwith('ex')     #判斷以什麼開始
print(v)

test = "username\temail\tpassword\nlaiying\tying@qq.com\t123\nlaiying\tying@qq.com\t123\nlaiying\tying@qq.com\t123"
v = test.expandtabs(20)         #\t是製表符,expandtabs,斷句20,到\t不足20補空格
print(v,len(v))



test = 'i am {name},age {a}'
print(test)
v = test.format(name='alex',a=19)  #格式化,將一個字串中的佔位符替換為指定的值
print(v)
test = 'i am {0},age {1}'
print(test)
v = test.format('alex',19)         #格式化,將一個字串中的佔位符替換為指定位置的值
print(v)

test = 'i am {name},age {a}'
v = test.format_map({"name":'alex',"a":19})  #格式化,傳入的值只能是字典
print(v)

test = 'aLexaLex'
v = test.index('ex',5,8)    #預設從開始往後找現在設定5到7的閉開區間
print(v)                   #找到第一個之後,獲取其位置,沒找到報錯

test = "uasf890"
v = test.isalnum()          #判斷字串中字串中是否只包含數字和字母
print(v)

test = "uasf"
v = test.isalpha()           #判斷字串中字串中是否只包含字母
print(v)

test = "二"
v1 = test.isdecimal()          #判斷字串中字串中是否只包含數字 2
v2 = test.isdigit()            #判斷字串中字串中是否只包含數字(還有數字符號)②
v3 = test.isnumeric()          #判斷字串中字串中是否只包含數字(還有數字符號、漢字)二
print(v1,v2,v3)

a = "la_123"
v = a.isidentifier()           #判斷標誌符 識別符號只包含,字母、數字、下劃線且首字母不是數字
print(v)

test = 'oiue\turyyffb'
v = test.isprintable()           #判斷字串是否存在不可顯示的字元\t製表\n換行
print(v)


test = ' '
v = test.isspace()                 #判斷字元全空格
print(v)

test = 'sdusdjnd and sdin is hwj'
v1 = test.istitle()                 #判斷標題,也是所有單詞首字母大寫
test1 = test.title()
v2 = test1.istitle()
print(v1,test1,v2)

v = 'aesdioujkdfhiudoiasdoiuf'
m = str.maketrans('aeiou','12345')  #設定前後對應關係
new_v = v.translate(m)              #對m中字元進行對應關係變換
print(new_v)

v = 'alexalex'
new_v = v.replace('ex','apeiou',2)     #對匹配到的序列替換,預設全替換,現在只替換前2個
print(new_v)

test = 'asdfadsf\nasdasfdsf\nsdfa'
v = test.splitlines(True)                #分割,只能根據,true,false;是否保留換行
print(v)

test = 'backend1.1.1.1'
v  = test.startswith('a')                #判斷以XXX開頭
v1 = test.endswith('a')                  #判斷以XXX結尾
print(v,v1)

test = 'aLex1'
v = test.swapcase()                      #大小寫轉換
print(v)
  • 列表
li = [11, 22, 33, 44]
v = li.append(5)     #直接修改list無返回值,元素做整體追加
print(li)
li = [11, 22, 33, 44]
li.extend([22])           #把元素迴圈擴充套件到列表中
print(li)

li = [11, 22, 33, 44]
li.clear()           #清空
print(li)

li = [11, 22, 33, 44]
v = li.copy()          #淺拷貝
print(v)

li = [11, 22, 33, 44]
v = li.count(22)         #計算元素出現的個數
print(v)

li = [11, 22, 33, 44]
v = li.index(22)           #根據值獲取當前值獲取位置
print(v)

li = [11, 22, 33, 22, 44]
li.insert(0, 99)           #在指定索引位置插入元素
print(li)

li = [11, 22, 33, 22, 44]
v = li.pop()               #預設刪除最後一個位置的值並返回當前值
print(li,v)

li = [11, 22, 33, 22, 44]
li.remove(11)               #刪除第一個指定值
print(li)

li = [11, 22, 33, 22, 44]
li.remove(11)               #刪除第一個指定值
print(li)

li = [11, 22, 33, 22, 44]
li.reverse()               #將當前列表反轉
print(li)

li = [11, 22, 33, 22, 44]
li.sort(reverse=True)               #列表從小到大排序,現在從大到小
print(li)


li = [1, 2, 43, [1, 2, 3], "age", "alex"]
for item in range(0, 5):
    print(li[item])
print(li[3][2])
li[1:3] = [1, 20, 32, 33]
print(li)
del li[1:3]
  • 元組
tu = (11, 22, 11, 33, 44,)
tu.count(11)      # 獲取指定元素在元組中出現次數
v = tu.index(11)  # 獲取指定元素在元組中第一個的位置
print(v)

tu = (111, 222, 333, )  # 元素不可被修改。

v = tu[0]

v = tu[0:2]

for item in range(0, 5):
    print(tu[item])

s = "djqwuidsdaf"
li = ["dgfhfsd", "djksd"]
tu = (123, 123, "asd")

v = list(tu)    #元組轉換列表
  • 字典
info = {
    "k1": "v1",      # 鍵值對
    "k2": "v2"
}
v = dict.fromkeys([123, 'k1', 999], 123)  # 根據序列建立字典,附上固定值
print(v)

v = info.get('k1')    # 獲取鍵值,key不存在,可以指定預設值
v = info.pop('k11', 90)    # 刪除並獲取值,如沒有返回指定值
v = info.popitem()     # 隨機刪除專案
print(v)

v = info.setdefault('k1', '123')   # 設定值,若key存在,獲取當前key對應的值。

info.update({'k1': '1111', 'k3': 123})
info.update(k1='1121', k3=123)       # 更新
print(info)


info = {            # 鍵值對鍵值的key必須是確定值,hashable轉換存
    2: "asd",
    "k1": 'sda',
    "k4": 'ssa',
    "k2": "v1",      # 鍵值對
    "k3": [22, 33, 44],
    True: 'sda',
    (10, 20): 'sda'
}
print(info)

del info[1]  # 根據k值尋找操作

for k, v in info.items():
    print(k, v)

  • 集合
s = frozenset('hello')        # 不可變集合
s = {1, 1, 2, 3, 4, 5, '1'}   # 去重,集合
s.pop()
s.pop()
s.remove(4)
v = s.discard(11)
print(s, v)

Python_1 = {'alex', 'apple', 'orange', 'alex'}
linux_1 = {'alex', 'apple', 'banana'}
p_s = set(Python_1)
l_s = set(linux_1)
print(p_s, l_s)
print(p_s.intersection(l_s))   # 合集
print(p_s & l_s)

print(p_s.union(l_s))   # 並集
print(p_s | l_s)

print(p_s - l_s)       # 差集
print(l_s.difference(p_s))       # 差集
print(p_s.difference_update(l_s),p_s)

print(p_s.symmetric_difference(l_s)) # 交叉補集
print(p_s ^ l_s)

s1 = {1, 2}
s2 = {3, 5}
print(s1.isdisjoint(s2))

s1 = {1, 2}
s2 = {1, 4, 3}
print(s1.issubset(s2))
print(s2.issuperset(s1))
s1.update(s2)           # 更新多個值比union多個賦值add()只能傳一個值
print(s1)

相關推薦

Python封裝函式strlisttupledictset

字元 encode decode test = 'aLexaLex' v = test.find('ex',5,7) #預設從開始往後找現在設定5到7的閉開區間 print(v) #找到第一個之後,獲取其

python 容器特點總結:listtupledictset

list:有序的,可重複的,可以儲存任何型別,可改變 tuple:有序的,不可變,可重複,可以儲存任何型別 set:無序的,可變,不可重複,(用於去重),可以儲存任何型別 dict:值鍵對, 無序的, 鍵不可重複,值可重複,鍵不可變,值可變,可以儲存任何型別

pythonlisttupledictset的區別及聯絡

我在python學習中遇到的一個與其他語言不太相同的一點就是list.tuple.dict.set這幾個資料型別的區別及聯絡。昨天學了,為防忘記,今天就來現學現賣。 一、list          俗稱列表,是一種有序集合。也就是說,list中的資料排列是有順序的。可以

listtupledictset

list Python內建的一種資料型別是列表:list。list是一種有序的集合,可以隨時新增和刪除其中的元素。 直接用 [ ] 把list的所有元素都括起來,就是一個list物件。 L = ['Adam', 'Lisa', 'Bart'] Python按照索

listtupledictset的主要區別

1 .list list是一個使用方括號括起來的有序元素集合; List 可以作為以 0 下標開始的陣列,任何一個非空 list 的第一個元素總是 L[0],負數索引從 list 的尾部開始向前計數來存取元素。任何一個非空的 list 最後一個元素總是 L[-1]; 有

python基礎二列表和元組(序列相加乘法成員資格)

這篇文章記載序列相加、乘法、成員資格等內容。 1、序列相加 看下面的例子: number1=[1,2,3] number2=[4,5,6] add=number1+number2; print("add:{}".format(add)) str1=["hello"] str2=["w

scala 模式匹配TypeArrayListTuple

1、程式碼 package com.yy.base /** * Scala 模式匹配 * Type Array List Tuple */ object PatternMatchMore extends App { println("-----Type

Python資料結構二叉樹(涵蓋了構建刪除查詢字典轉換非遞迴與遞迴遍歷等)

MyTree.py #coding=utf-8 import math class BinTree: def __init__(self): self.root=None def is_empty(self):

java的知識點23——泛型GenericsCollection介面List特點和常用方法 ArrayList特點和底層實現

泛型Generics 一般通過“容器”來容納和管理資料。程式中的“容器”就是用來容納和管理資料。 陣列就是一種容器,可以在其中放置物件或基本型別資料。 陣列的優勢:是一種簡單的線性序列,可以快速地訪問陣列元素,效率高。如果從效率和型別檢查的角度講,陣列是最好的。 陣列的劣勢:不靈活。

python魔法函式__getitem__

魔法函式會增強python類的型別,獨立存在 class Company: def __init__(self, employees): self.employees = employees def __getitem__(self, item): retu

python神奇函式eval()學習

python中有很多內建的很有用的工具函式,熟練地使用這些小工具絕對可以幫助你在工作中達到事半功倍的效果,今天由於需要用到了eval()函式,這個函式其實之前就用過了但是由於最近一直忙於看論文和方向上的一些其他的事,這個東西也就慢慢忘掉了,今天要用,索性直接再學一下,這裡就作

python魔法函式__getattr__與__getattribute__

getattr 在訪問物件的屬性不存在時,呼叫__getattr__,如果沒有定義該魔法函式會報錯 class Test: def __init__(self, name, age): self.name = name self.age = age

Python資料型別str相關常用操作

name = "my \tname is alex" print(name.capitalize())  #首字母大寫 print(name.count("a"))    #統計字母的重複數量 print(name.center(50,"-"))

python資料型別str

一、strl型別 1、索引和切片       索引:索引從左到右,從零開始。 i1 = '1234567' i2 = i1[3] i3 = i1[-1] #從頭取,可以不寫 pri

python的數據類型--listtuple

指定元素 之間 有序 刪除指定元素 opp pen 元組 color col list是Python的一種數據類型,是一個有序的集合,可以隨時添加和刪除。寫法為list名稱+[] list[]內的元素不僅僅為str,可以是數字,布爾值。 訪問方法為變量名或者變量[索引],和

python初級資料結構(listtupledict)(補充筆記,初級)

List: 遞推式構造列表(List Comprehension),例: list = [x*2 for x in lm] 切片list[start: stop: step] sort 和 sorted: sort會改變list(in-place),而sorted返回排序好的列表(retu

Python聽課筆記---內建結構listtuplesetdict

** 一、列表list ** append() 在末尾插入一個內容 insert(index,data) 指定位置插入 如:a.insert(3,11)在第四個位置插入11 del() 刪除 pop()拿出最後一個元素,經常有賦值操作如:a=x.pop() r

Python內建的有序集合listtuple

list----一種有序集合 classmates=['Mike','Bob','Tom'] classmates[-1]--------Tom,即倒數第一個 classmates[-2]--------Bob,即倒數第二個   classmates.append('A

Python開發的入門教程(二)-ListTuple型別

# 介紹 本文主要介紹Python中List和Tuple型別的基本知識和使用。 ## Python建立list Python內建的一種資料型別是列表:list。list是一種有序的集合,可以隨時新增和刪除其中的元素。 比如,列出班裡所有同學的名字,就可以用一個list表示: ``` >>&

分別把 string, listtupledict寫入到文件中

寫文件import codecs list = [‘2‘,‘4‘,‘3‘,‘9‘,‘1‘,‘7‘] # 列表 tul = (‘a‘,‘b‘,‘b‘,‘e‘,‘b‘) # 元組 k={‘name‘:‘zhouyuyao‘,‘age‘:21} # 字典 f=codecs.o