python切片如何作为占位符使用
python切片如何作为占位符使用
本文教程操作环境:windows7系统、Python3.9.1,DELLG3电脑。
1、切片说明
切片既可以作为独立对象被“取出”原序列,也可以留在原序列,作为一种占位符使用。
2、占位符的使用
拼接字符串的方法,其中三种格式化类的拼接方法(即%、format()、template)就是使用了占位符的思想。对于列表来说,使用切片作为占位符,同样能够实现拼接列表的效果。特别需要注意的是,给切片赋值的必须是可迭代对象。
3、实例
li=[1,2,3,4]
#在头部拼接
li[:0]=[0]#[0,1,2,3,4]
#在末尾拼接
li[len(li):]=[5,7]#[0,1,2,3,4,5,7]
#在中部拼接
li[6:6]=[6]#[0,1,2,3,4,5,6,7]
#给切片赋值的必须是可迭代对象
li[-1:-1]=6#(报错,TypeError:canonlyassignaniterable)
li[:0]=(9,)#[9,0,1,2,3,4,5,6,7]
li[:0]=range(3)#[0,1,2,9,0,1,2,3,4,5,6,7]
上述例子中,若将切片作为独立对象取出,那你会发现它们都是空列表,即li[:0]==li[len(li):]==li[6:6]==[],我将这种占位符称为“纯占位符”,对纯占位符赋值,并不会破坏原有的元素,只会在特定的索引位置中拼接进新的元素。删除纯占位符时,也不会影响列表中的元素。
以上就是python切片作为占位符的使用方法,大家在看完本篇文章,不妨动手尝试,用切片作为占位符的方法来对列表进行拼接吧。更多Python学习教程请关注IT培训机构:千锋教育。

相关推荐HOT
更多>>
python中s3cmd是什么?
python中s3cmd是什么?本文教程操作环境:windows7系统、Python3.9.1,DELLG3电脑。简单介绍:可以实现使用s3对象存储安装方式:yuminstalls3cmd...详情>>
2023-11-14 19:15:02
python中如何使用pandas实现行数据添加
python中如何使用pandas实现行数据添加python中,pandas是一个数据分析包,可以对数据进行很方便的处理提供了高效地操作大型数据集所需的工具。...详情>>
2023-11-14 16:35:59
python迭代器中Yield方法怎么用?
python迭代器中Yield方法怎么用?Yield用于返回数据,程序执行到yield后,返回结果,记住当前状态,暂停执行,下次调用时,根据上次的状态,返回...详情>>
2023-11-14 16:11:13
python元组拆包如何实现?
python元组拆包如何实现?1、说明把元组一一对应拆出来,就叫做元组拆包。拆包有个要求,元组中的元素数量必须跟接受这些元素的空挡数一致,否则...详情>>
2023-11-14 13:24:22热门推荐
python中any函数如何使用?
沸python operator模块有何用法?
热python中s3cmd是什么?
热python中getattribute方法作用是什么?
新python如何使用TemporaryFile()方法创建临时文件?
python中sys模块是什么?
python的ndarray与pandas的series如何相互转换?
python中如何使用pandas实现行数据添加
python迭代器中Yield方法怎么用?
python中temp是什么意思?
python中Cartopy是什么
python入门:方差和标准差的区别
python切片如何作为占位符使用
python元组拆包如何实现?
技术干货






