Python3 實例(六)

Python 判斷字符串是否存在子字符串

給定一個字符串,然後判斷指定的子字符串是否存在於改字符串中。

實例

def check(string, sub_str):
if (string.find(sub_str) == -1):
print("不存在!")
else:
print("存在!")

string = "www.runoob.com"
sub_str ="runoob"
check(string, sub_str)
執行以上代碼輸出結果爲:

存在!
Python 判斷字符串長度

給定一個字符串,然後判斷改字符串的長度。

實例 1:使用內置方法 len()

str = "runoob"
print(len(str))
執行以上代碼輸出結果爲:

6
實例 2:使用循環計算

def findLen(str):
counter = 0
while str[counter:]:
counter += 1
returncounter

str = "runoob"
print(findLen(str))
執行以上代碼輸出結果爲:

6
Python 使用正則表達式提取字符串中的 URL

給定一個字符串,裏面包含 URL 地址,需要我們使用正則表達式來獲取字符串的 URL。

實例

import re

def Find(string):

findall() 查找匹配正則表達式的字符串

url = re.findall('https?://(?:[-\w.]|(?:%[\da-fA-F]{2}))+', string)
return url 

string = 'Runoob 的網頁地址爲:https://www.runoob.com,Google 的網頁地址爲:https://www.google.com'
print("Urls: ", Find(string))
執行以上代碼輸出結果爲:

Urls: ['https://www.runoob.com', 'https://www.google.com']
Python 將字符串作爲代碼執行

給定一個字符串代碼,然後使用 exec() 來執行字符串代碼。

實例 1:使用內置方法 len()

def exec_code():
LOC = """
def factorial(num):
fact=1
for i in range(1,num+1):
fact = fact*i
return fact
print(factorial(5))
"""
exec(LOC)

exec_code()
執行以上代碼輸出結果爲:

120
Python 字符串翻轉

給定一個字符串,然後將其翻轉,逆序輸出。

實例 1:使用字符串切片

str='Runoob'
print(str[::-1])
執行以上代碼輸出結果爲:

boonuR
實例 2:使用 reversed()

str='Runoob'
print(''.join(reversed(str)))
執行以上代碼輸出結果爲:

boonuR
Python 對字符串切片及翻轉

給定一個字符串,從頭部或尾部截取指定數量的字符串,然後將其翻轉拼接。

實例

def rotate(input,d):

Lfirst = input[0 : d] 
Lsecond = input[d :] 
Rfirst = input[0 : len(input)-d] 
Rsecond = input[len(input)-d : ] 

print( "頭部切片翻轉 : ", (Lsecond + Lfirst) )
print( "尾部切片翻轉 : ", (Rsecond + Rfirst) )

if name == "main":
input = 'Runoob'
d=2 # 截取兩個字符
rotate(input,d)
執行以上代碼輸出結果爲:

頭部切片翻轉 : noobRu
尾部切片翻轉 : obRuno
Python 按鍵(key)或值(value)對字典進行排序

給定一個字典,然後按鍵(key)或值(value)對字典進行排序。

實例1:按鍵(key)排序

def dictionairy():

# 聲明字典
key_value ={}     

# 初始化
key_value[2] = 56       
key_value[1] = 2 
key_value[5] = 12 
key_value[4] = 24
key_value[6] = 18      
key_value[3] = 323 

print ("按鍵(key)排序:")   

# sorted(key_value) 返回一個迭代器
# 字典按鍵排序
for i in sorted (key_value) : 
    print ((i, key_value[i]), end =" ") 

def main():

調用函數

dictionairy() 

主函數

if name=="main":
main()
執行以上代碼輸出結果爲:

按鍵(key)排序:
(1, 2) (2, 56) (3, 323) (4, 24) (5, 12) (6, 18)
實例2:按值(value)排序

def dictionairy():

# 聲明字典
key_value ={}     

# 初始化
key_value[2] = 56       
key_value[1] = 2 
key_value[5] = 12 
key_value[4] = 24
key_value[6] = 18      
key_value[3] = 323 

print ("按值(value)排序:")   
print(sorted(key_value.items(), key = lambda kv:(kv[1], kv[0])))   

def main():
dictionairy()

if name=="main":
main()
執行以上代碼輸出結果爲:

按值(value)排序:
[(1, 2), (5, 12), (6, 18), (4, 24), (2, 56), (3, 323)]
實例 3 : 字典列表排序

lis = [{ "name" : "Taobao", "age" : 100},
{ "name" : "Runoob", "age" : 7 },
{ "name" : "Google", "age" : 100 },
{ "name" : "Wiki" , "age" : 200 }]

通過 age 升序排序

print ("列表通過 age 升序排序: ")
print (sorted(lis, key = lambda i: i['age']) )

print ("\r")

先按 age 排序,再按 name 排序

print ("列表通過 age 和 name 排序: ")
print (sorted(lis, key = lambda i: (i['age'], i['name'])) )

print ("\r")

按 age 降序排序

print ("列表通過 age 降序排序: ")
print (sorted(lis, key = lambda i: i['age'],reverse=True) )
執行以上代碼輸出結果爲:

列表通過 age 升序排序:
[{'name': 'Runoob', 'age': 7}, {'name': 'Taobao', 'age': 100}, {'name': 'Google', 'age': 100}, {'name': 'Wiki', 'age': 200}]

列表通過 age 和 name 排序:
[{'name': 'Runoob', 'age': 7}, {'name': 'Google', 'age': 100}, {'name': 'Taobao', 'age': 100}, {'name': 'Wiki', 'age': 200}]

列表通過 age 降序排序:
[{'name': 'Wiki', 'age': 200}, {'name': 'Taobao', 'age': 100}, {'name': 'Google', 'age': 100}, {'name': 'Runoob', 'age': 7}]
Python 計算字典值之和

給定一個字典,然後計算它們所有數字值的和。

實例

def returnSum(myDict):

sum = 0
for i in myDict: 
    sum = sum + myDict[i] 

return sum

dict = {'a': 100, 'b':200, 'c':300}
print("Sum :", returnSum(dict))
執行以上代碼輸出結果爲:

Sum : 600
Python 移除字典點鍵值(key/value)對

給定一個字典,然後計算它們所有數字值的和。

實例 1 : 使用 del 移除

test_dict = {"Runoob" : 1, "Google" : 2, "Taobao" : 3, "Zhihu" : 4}

輸出原始的字典

print ("字典移除前 : " + str(test_dict))

使用 del 移除 Zhihu

deltest_dict['Zhihu']

輸出移除後的字典

print ("字典移除後 : " + str(test_dict))

移除沒有的 key 會報錯

#del test_dict['Baidu']
執行以上代碼輸出結果爲:

字典移除前 : {'Runoob': 1, 'Google': 2, 'Taobao': 3, 'Zhihu': 4}
字典移除後 : {'Runoob': 1, 'Google': 2, 'Taobao': 3}
實例 2 : 使用 pop() 移除

test_dict = {"Runoob" : 1, "Google" : 2, "Taobao" : 3, "Zhihu" : 4}

輸出原始的字典

print ("字典移除前 : " + str(test_dict))

使用 pop 移除 Zhihu

removed_value = test_dict.pop('Zhihu')

輸出移除後的字典

print ("字典移除後 : " + str(test_dict))

print ("移除的 key 對應的 value 爲 : " + str(removed_value))

print ('\r')

使用 pop() 移除沒有的 key 不會發生異常,我們可以自定義提示信息

removed_value = test_dict.pop('Baidu', '沒有該鍵(key)')

輸出移除後的字典

print ("字典移除後 : " + str(test_dict))
print ("移除的值爲 : " + str(removed_value))
執行以上代碼輸出結果爲:

字典移除前 : {'Runoob': 1, 'Google': 2, 'Taobao': 3, 'Zhihu': 4}
字典移除後 : {'Runoob': 1, 'Google': 2, 'Taobao': 3}
移除的 key 對應的 value 爲 : 4

字典移除後 : {'Runoob': 1, 'Google': 2, 'Taobao': 3}
移除的值爲 : 沒有該鍵(key)
實例 3 : 使用 items() 移除

test_dict = {"Runoob" : 1, "Google" : 2, "Taobao" : 3, "Zhihu" : 4}

輸出原始的字典

print ("字典移除前 : " + str(test_dict))

使用 pop 移除 Zhihu

new_dict = {key:valfor key, val in test_dict.items() if key != 'Zhihu'}

#

執行以上代碼輸出結果爲:

字典移除前 : {'Runoob': 1, 'Google': 2, 'Taobao': 3, 'Zhihu': 4}
字典移除後 : {'Runoob': 1, 'Google': 2, 'Taobao': 3}
Python 合併字典

給定一個字典,然後計算它們所有數字值的和。

實例 1 : 使用 update() 方法,第二個參數合併第一個參數

def Merge(dict1, dict2):
return(dict2.update(dict1))

兩個字典

dict1 = {'a': 10, 'b': 8}
dict2 = {'d': 6, 'c': 4}

返回 None

print(Merge(dict1, dict2))

dict2 合併了 dict1

print(dict2)
執行以上代碼輸出結果爲:

None{'d': 6, 'c': 4, 'a': 10, 'b': 8}
實例 2 : 使用 **,函數將參數以字典的形式導入

def Merge(dict1, dict2):
res = {dict1, dict2}
return res

兩個字典

dict1 = {'a': 10, 'b': 8}
dict2 = {'d': 6, 'c': 4}
dict3 = Merge(dict1, dict2) print(dict3)
執行以上代碼輸出結果爲:

{'a': 10, 'b': 8, 'd': 6, 'c': 4}

好了,本文就給大夥分享到這裏,文末分享一波福利

Python3 實例(六)

Python3 實例(六)

獲取方式:加python羣 839383765 即可獲取!

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