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 相关文章推荐
在Linux下使用Python的matplotlib绘制数据图的教程
Jun 11 Python
Python的包管理器pip更换软件源的方法详解
Jun 20 Python
python numpy元素的区间查找方法
Nov 14 Python
Python设计模式之策略模式实例详解
Jan 21 Python
selenium+python自动化测试之多窗口切换
Jan 23 Python
python替换字符串中的子串图文步骤
Jun 19 Python
Python实现ATM系统
Feb 17 Python
Python要如何实现列表排序的几种方法
Feb 21 Python
Python求解排列中的逆序数个数实例
May 03 Python
Python字典实现伪切片功能
Oct 28 Python
Python可视化学习之seaborn调色盘
Feb 24 Python
python使用torch随机初始化参数
Mar 22 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
德生PL990的分析评价
2021/03/02 无线电
一键删除顽固的空文件夹 软件下载
2007/01/26 PHP
php addslashes及其他清除空格的方法是不安全的
2012/01/25 PHP
php增删改查示例自己写的demo
2013/09/04 PHP
PHP判断远程图片是否存在的几种方法
2014/05/04 PHP
php单一接口的实现方法
2015/06/20 PHP
PHP校验15位和18位身份证号的类封装
2018/11/07 PHP
laravel实现图片上传预览,及编辑时可更换图片,并实时变化的例子
2019/11/14 PHP
用showModalDialog弹出页面后,提交表单总是弹出一个新窗口
2009/07/18 Javascript
Js切换功能的简单方法
2010/11/23 Javascript
Jquery进度条插件 Progress Bar小问题解决
2011/07/12 Javascript
js实现文字超出部分用省略号代替实例代码
2016/09/01 Javascript
学习 NodeJS 第八天:Socket 通讯实例
2016/12/21 NodeJs
简单实现js鼠标跟随效果
2020/08/02 Javascript
Bootstrap模态对话框中显示动态内容的方法
2018/08/10 Javascript
Vue-Quill-Editor富文本编辑器的使用教程
2018/09/21 Javascript
js 实现碰撞检测的示例
2020/10/28 Javascript
Python isinstance判断对象类型
2008/09/06 Python
Python创建模块及模块导入的方法
2015/05/27 Python
python+selenium实现京东自动登录及秒杀功能
2017/11/18 Python
Python列表推导式、字典推导式与集合推导式用法实例分析
2018/02/07 Python
Python学习笔记之Django创建第一个数据库模型的方法
2019/08/07 Python
Python3 中sorted() 函数的用法
2020/03/24 Python
keras实现theano和tensorflow训练的模型相互转换
2020/06/19 Python
CSS3实现翘边的阴影效果的代码示例
2016/06/13 HTML / CSS
西班牙太阳镜品牌:Hawkers
2018/03/11 全球购物
试解释COMMIT操作和ROLLBACK操作的语义
2014/07/25 面试题
护士上岗前培训自我鉴定
2014/04/20 职场文书
《称象》教学反思
2014/04/25 职场文书
商业项目策划方案
2014/06/05 职场文书
单位委托函范文
2015/01/29 职场文书
2015年“七七卢沟桥事变”纪念活动总结
2015/03/24 职场文书
事业单位岗位说明书
2015/10/08 职场文书
军训心得体会范文(2016最新篇)
2016/01/11 职场文书
2016年度先进班组事迹材料
2016/03/01 职场文书
Python如何把不同类型数据的json序列化
2021/04/30 Python