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}

好了,本文就给大伙分享到这里,文末分享一波福利

获取方式:加python群 839383765 即可获取!

原文地址:https://blog.51cto.com/14186420/2407523

时间: 2024-08-30 15:16:01

Python3 实例(六)的相关文章

ASP.NET MVC3 实例(六) 增加、修改和删除操作(二)

http://www.jquery001.com/asp.net-mvc3-instance-add-update-delete2.html 上篇我们在 ASP.NET MVC3 中实现了添加操作,由于时间关系没有完成修改.删除操作,我们新建了一个名为"Contact"的 Controller,并实现了添加方法,下边就让我们在此基础上来完成 ASP.NET MVC3 中的修改和删除操作. 首先,我们在 Contact 控制器类中添加一个名为 View()的方法,用来从 Contact

android4.0 USB Camera实例(六)ffmpeg mpeg编码

前面本来说是做h264编码的 研究了两天发现ffmpeg里的h264编码似乎是要信赖第三方库x264 还是怎么简单怎么来吧所以就整了个mpeg编码 ffmpeg移植前面我有一篇ffmpeg解码里已经给了 具体链接在这http://blog.csdn.net/hclydao/article/details/18546757 怎么使用那里面也已经说了 这里主要是通过ffmpeg将yuv422格式转换成rgb 然后就是yuv422转成mpeg格式 接前面几篇 获取到yuv422数据后 为了能显示出来

C语言库函数大全及应用实例六

原文:C语言库函数大全及应用实例六                                              [编程资料]C语言库函数大全及应用实例六 函数名: getlinesettings 功 能: 取当前线型.模式和宽度 用 法: void far getlinesettings(struct linesettingstype far *lininfo): 程序例: #i nclude #i nclude #i nclude #i nclude /* the names o

Python3 实例(二)

Python 判断字符串是否为数字 以下实例通过创建自定义函数 is_number() 方法来判断字符串是否为数字: 实例(Python 3.0+) -- coding: UTF-8 -- Filename : test.py author by : www.runoob.com def is_number(s):try: float(s)return Trueexcept ValueError: pass try: import unicodedata unicodedata.numeric(

Python3 实例

Python 判断字符串是否为数字 以下实例通过创建自定义函数 is_number() 方法来判断字符串是否为数字: 实例(Python 3.0+) # -*- coding: UTF-8 -*-# Filename : test.py# author by : www.runoob.comdef is_number(s): try: float(s) return True except ValueError: pass try: import unicodedata unicodedata.

Python3 实例(三)

Python 十进制转二进制.八进制.十六进制 以下代码用于实现十进制转二进制.八进制.十六进制: 实例(Python 3.0+) -- coding: UTF-8 -- Filename : test.py author by : www.runoob.com 获取用户输入十进制数 dec = int(input("输入数字:")) print("十进制数为:", dec)print("转换为二进制为:", bin(dec))print(&qu

Python3 实例(八)

Python 归并排序 归并排序(英语:Merge sort,或mergesort),是创建在归并操作上的一种有效的排序算法.该算法是采用分治法(Divide and Conquer)的一个非常典型的应用. 分治法: 分割:递归地把当前序列平均分割成两半. 集成:在保持元素顺序的同时将上一步得到的子序列集成到一起(归并). 实例 def merge(arr, l, m, r): n1 = m - l + 1n2 = r- m # 创建临时数组 L = [0] * (n1) R = [0] * (

python 实例六

题目:斐波那契数列. 程序分析:这个数列从第3项开始,每一项都等于前两项之和.故 n=1,2,f=1 n>2,f=f(n-1)+f(n-2) 例如:1,1,2,3,5,8..... >>> def f6(n): if n==1 or n==2: return 1 elif n>2: return f6(n-1)+f6(n-2) else: print 'please input an incorrect number' >>> for i in range(

循序渐进Python3(六) -- 面向对象

Python 面向对象 什么是面向对象编程? 面向对象编程是一种程序设计范式 对现实世界建立对象模型 把程序看作不同对象的相互调用 Python从设计之初就已经是一门面向对象的语言,正因为如此,在Python中创建一个类和对象是很容易的.下面我们将详细介绍Python的面向对象编程. 如果你以前没有接触过面向对象的编程语言,那你可能需要先了解一些面向对象语言的一些基本特征,在头脑里头形成一个基本的面向对象的概念,这样有助于你更容易的学习Python的面向对象编程. 接下来我们先来简单的了解下面向