Python字符串、列表、元组、字典、集合的补充实例详解


Posted in Python onDecember 20, 2019

本文实例讲述了Python字符串、列表、元组、字典、集合。分享给大家供大家参考,具体如下:

附加:

python的很多编译器提供了代码补全功能,并且在填入参数时提供提示功能

Python字符串、列表、元组、字典、集合的补充实例详解

Python字符串、列表、元组、字典、集合的补充实例详解

字符串

1.常用函数:

字符串是不可变对象,字符串的方法都不会改变原字符串的数据

s=" hEllo world!\t "
print("s.capitalize():",s.capitalize())#标题格式化
print("s.center(20,'-'):",s.center(20,'-'))#将字符串居中填充,填充元素为指定字符,总字符数为指定数量
print("s.count('l'):",s.count('l'))#统计某字符串出现次数
print("s.endswith:",s.endswith('d!'))#判断字符串是否以d!结尾
print("s.find('o'):",s.find('o'))#查找指定元素,找到返回其索引
print("s.index('o'):",s.index('o'))#查找指定元素,找到返回其索引
sep='ABC'
print("s.join(sep):",s.join(sep))#将原字符s插入到目标的每一个字符(或元素对象)中间
print("s.lower():",s.lower())#全转成小写
print("s.replace('l','j',1):",s.replace('l','j',1))#替换指定字符,最后一个是替换数量
print("s.split():",s.split())#切割字符串,切割字符为指定字符
print("s.strip():",s.strip())#去除左右空格元素,rstrip是只去除右边,lstrip是只去除右边
print("s.upper():",s.upper())#全转大写
"""is系列:
isdigit()-》是否是数字,isalnum()-》是否为字母或数字,isalpha()-》是否为英文字母
islower()-》是否全小写,
"""

上诉代码结果:

s.capitalize():  hello world!    
s.center(20,'-'): -- hEllo world!     ---
s.count('l'): 3
s.endswith: False
s.find('o'): 5
s.index('o'): 5
s.join(sep): A hEllo world!     B hEllo world!     C
s.lower():  hello world!    
s.replace('l','j',1):  hEjlo world!    
s.split(): ['hEllo', 'world!']
s.strip(): hEllo world!
s.upper():  HELLO WORLD!

2.字符串格式化:

python 字符串格式化--这个好像参数给的好全

>>> s="%d is 250"
>>> s%250
'250 is 250'
>>> b = "%(name)+10s————————%(age)-10d————————"%{'name':'xx','age':20}
>>> print(b)
    xx————————20    ————————
>>> s="{:d} is a 250"
>>> s.format(250)
'250 is a 250'
>>> a1 = "numbers: {:b},{:o},{:d},{:x},{:X}, {:%},{:c}".format(15, 15, 15, 15, 15, 15.87623,65)
>>> print(a1)
numbers: 1111,17,15,f,F, 1587.623000%,A
>>> s="{} {} 250"
>>> s.format(250,"500-250")
'250 500-250 250'
>>> s.format(250,"500-250")
'250 500-250 250'

3.原始字符串:

起因:为了避免过多使用\来转义,当字符串格式为   r"字符串" 时 里面的字符全部当成字符,如\n不再当初换行

>>> print("a\tb")
a  b
>>> print(r"a\tb")
a\tb

但字符串无法处理,如果结尾是一个  \ :

>>> print(r"c:\a\b")
c:\a\b
>>> print(r"c:\a\b\")
SyntaxError: EOL while scanning string literal
>>> print(r"c:\a\b\\")
c:\a\b\\
>>> print(r"c:\a\b"+"\\")
c:\a\b\

这样的情况最好使用字符串拼接来处理。

列表

1.常用函数:

print("查".center(20,'-'))
list_find=['apple','banana','pen',1,2,3]
#查找指定元素的下标
print(list_find.index('apple'))
#查找某元素存在的数量
print(list_find.count("apple"))
print("增".center(20,'-'))
list_add=['apple','banana']
#追加元素到末尾
list_add.append("哈密瓜")
print(list_add)
#插入元素到指定位置
list_add.insert(0,"苹果")
print(list_add)
print("删".center(20,'-'))
list_del=[1,2,3,4,"apple",5,6,7,8]
#从列表中取出元素(删除式取出),pop可以填参数,参数为删除元素的下标
list_del.pop()
print(list_del)
#remove删除指定元素名的元素
list_del.remove("apple")
print(list_del)
#删除对应元素空间
del list_del[0]
print(list_del)
print("其他".center(20,'-'))
list_test4=['a','b','d','c']
list_test5=[1,2,3,4]
#扩展列表
list_test5.extend(list_test4)
print(list_test5)
#对列表进行排序
list_test4.sort()
print(list_test4)#注:py3无法对元素类型不同的进行排序
#反转列表
list_test5.reverse()
print(list_test5)

上述代码运行结果:

---------查----------
0
1
---------增----------
['apple', 'banana', '哈密瓜']
['苹果', 'apple', 'banana', '哈密瓜']
---------删----------
[1, 2, 3, 4, 'apple', 5, 6, 7]
[1, 2, 3, 4, 5, 6, 7]
[2, 3, 4, 5, 6, 7]
---------其他---------
[1, 2, 3, 4, 'a', 'b', 'd', 'c']
['a', 'b', 'c', 'd']
['c', 'd', 'b', 'a', 4, 3, 2, 1]

2.列表生成式:

# 过程:1.迭代 迭代器 中的每个元素;
# 2.每次迭代都先把结果赋值给变量,然后通过代入表达式得到一个新的计算值;
#3. 最后把所有表达式得到的计算值以一个新列表的形式返回。
print("普通的列表生成式".center(50,'-'))
#[表达式 for 变量 in 迭代器]
list1=[i for i in range(10)]
print(list1)
list2=[i*i for i in range(10,20)]
print(list2)
print("\n")
print("带判断的列表生成式".center(50,'-'))
#[表达式 for 变量 in 迭代器 if 表达式]
list3=[i for i in range(10) if i%2==0]
print(list3)
print("\n")
print("嵌套循环的列表生成式".center(50,'-'))
#[表达式 for 变量 in 迭代器 for 变量 in 迭代器]
list4=[x*y for x in range(5) for y in range(5)]
print(list4)
print("\n")

上述代码运行结果:

---------------------普通的列表生成式---------------------
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[100, 121, 144, 169, 196, 225, 256, 289, 324, 361]

--------------------带判断的列表生成式---------------------
[0, 2, 4, 6, 8]

--------------------嵌套循环的列表生成式--------------------
[0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 0, 2, 4, 6, 8, 0, 3, 6, 9, 12, 0, 4, 8, 12, 16]

字典

1.常用函数:

d1={1:"苹果","雪碧":"雪梨"}
d1.clear()#清空字典
print(d1)
d1={1:"苹果","雪碧":"雪梨"}
print(d1.get(1))#获取字典的指定键的结果
print(d1.get(3))#如果获取不存在的键,返回None
print(d1.items())#获取字典的所有键值对
print(d1.keys())#获取字典的键
print(d1.values())#获取字典的值
print(d1.pop(1))#取出指定下标结果
print(d1.popitem())#不需索引的弹出结果
print(d1)
d1={1:"苹果","雪碧":"雪梨"}
d1.update({1:'apple',3:'pen'})#更新结果,同键名更新,新键名则添加结果
print(d1)

上述代码运行结果:

{}
苹果
None
dict_items([(1, '苹果'), ('雪碧', '雪梨')])
dict_keys([1, '雪碧'])
dict_values(['苹果', '雪梨'])
苹果
('雪碧', '雪梨')
{}
{1: 'apple', '雪碧': '雪梨', 3: 'pen'}

集合

1.常用函数:

s1=set(['a','b','c'])
print(s1.pop())#随机删除集合中的某个元素,取到元素后返回元素的值
print(s1)
s3={'a','d'}
s1.update(s3)#更新
print(s1)
s1.add('f')#增加元素
print(s1)
s1.clear()#清空
s1=set(['a','b','c','f'])
print(s1)
s1.remove('a')#删除目标元素,但集合中如无元素,会报错
print(s1)
s1.discard('g')#如果集合中无元素,不报错;有元素,就删除
print(s1)
b={'a','b','g'}
print("s1.difference(b)")
print(s1.difference(b))# 取集合s中有,b中没有的元素,并返回由此元素组成的集合
print("s1.interscetion(b)")
print(s1.intersection(b))#交集,两s和b中的交集,返回s,b中都存在的元素组成的集合
print("s1.issubset(b)")
print(s1.issubset(b))#判断s是否是b的子集
print("s1.issuperset(b)")
print(s1.issuperset(b)) #判断s是否是b的父集
print("s1.symmetric_difference(b)")
print(s1.symmetric_difference(b)) #取差集,并创建一个新的集合
print("s1.union(b)")
print(s1.union(b)) #并集
print("symmetric_difference_update")
print(s1)
s1.symmetric_difference_update(b)#无返回值
print(s1)
"""
xxxx_update的会覆盖s1的值,如:
s1.symmetric_difference_update()
得出symmetric_difference的结果后会覆盖s1的值
"""

上述代码结果:

a
{'c', 'b'}
{'c', 'b', 'd', 'a'}
{'c', 'b', 'd', 'f', 'a'}
{'a', 'c', 'b', 'f'}
{'c', 'b', 'f'}
{'c', 'b', 'f'}
s1.difference(b)
{'c', 'f'}
s1.interscetion(b)
{'b'}
s1.issubset(b)
False
s1.issuperset(b)
False
s1.symmetric_difference(b)
{'a', 'g', 'c', 'f'}
s1.union(b)
{'g', 'c', 'b', 'f', 'a'}
symmetric_difference_update
{'c', 'b', 'f'}
None
{'g', 'c', 'f', 'a'}

希望本文所述对大家Python程序设计有所帮助。

Python 相关文章推荐
批处理与python代码混合编程的方法
May 19 Python
Python脚本实时处理log文件的方法
Nov 21 Python
Pycharm技巧之代码跳转该如何回退
Jul 16 Python
Python 实现网页自动截图的示例讲解
May 17 Python
Python 实现Windows开机运行某软件的方法
Oct 14 Python
python+os根据文件名自动生成文本
Mar 21 Python
python 实现GUI(图形用户界面)编程详解
Jul 17 Python
python:删除离群值操作(每一行为一类数据)
Jun 08 Python
keras 简单 lstm实例(基于one-hot编码)
Jul 02 Python
python interpolate插值实例
Jul 06 Python
python 检测nginx服务邮件报警的脚本
Dec 31 Python
numpy数据类型dtype转换实现
Apr 24 Python
python获取网络图片方法及整理过程详解
Dec 20 #Python
python序列化与数据持久化实例详解
Dec 20 #Python
爬虫代理池Python3WebSpider源代码测试过程解析
Dec 20 #Python
python3的UnicodeDecodeError解决方法
Dec 20 #Python
基于python调用psutil模块过程解析
Dec 20 #Python
python如何使用jt400.jar包代码实例
Dec 20 #Python
基于python使用tibco ems代码实例
Dec 20 #Python
You might like
php导入导出excel实例
2013/10/25 PHP
php通过baihui网API实现读取word文档并展示
2015/06/22 PHP
PHP抽奖算法程序代码分享
2015/10/08 PHP
php7 list()、session及其他模块的修改实例分析
2020/05/25 PHP
javascript中"/"运算符常见错误
2010/10/13 Javascript
JavaScript高级程序设计 阅读笔记(十二) js内置对象Math
2012/08/14 Javascript
Javascript中查找不以XX字符结尾的单词示例代码
2013/10/15 Javascript
sails框架的学习指南
2014/12/22 Javascript
莱鸟介绍javascript onclick事件
2016/01/06 Javascript
Vue中fragment.js使用方法详解
2017/03/09 Javascript
详解使用PM2管理nodejs进程
2017/10/24 NodeJs
基于vue.js无缝滚动效果
2018/01/25 Javascript
vue之浏览器存储方法封装实例
2018/03/15 Javascript
谈谈React中的Render Props模式
2018/12/06 Javascript
[55:03]LGD vs EG 2018国际邀请赛小组赛BO2 第二场 8.17
2018/08/18 DOTA
Django应用程序中如何发送电子邮件详解
2017/02/04 Python
Python实现的排列组合计算操作示例
2017/10/13 Python
Python实现PS图像明亮度调整效果示例
2018/01/23 Python
python之从文件读取数据到list的实例讲解
2018/04/19 Python
python批量修改图片后缀的方法(png到jpg)
2018/10/25 Python
Python何时应该使用Lambda函数
2019/07/02 Python
tensorflow 大于某个值为1,小于为0的实例
2020/06/30 Python
浅析Python的命名空间与作用域
2020/11/25 Python
html5实现移动端适配完美写法
2017/11/16 HTML / CSS
Ann Taylor官方网站:美国最大的女性产品制造商之一
2016/09/14 全球购物
中专生求职自荐信范文
2013/12/22 职场文书
审计主管岗位职责
2014/01/31 职场文书
扩大国家免疫规划实施方案
2014/03/21 职场文书
公司委托书范本
2014/04/04 职场文书
校庆口号
2014/06/20 职场文书
群众路线班子对照检查材料
2014/09/25 职场文书
党委领导班子整改方案
2014/09/30 职场文书
2015年植树节活动总结
2015/02/06 职场文书
党支部书记岗位职责
2015/02/15 职场文书
投资合作意向书范本
2015/05/08 职场文书
2015年政教主任工作总结
2015/07/23 职场文书