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 即可获取!

转载于:https://blog.51cto.com/14186420/2407523

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值