Python中的切片符号
Python符号
slice()函数返回一个切片对象。的slice()object用于切片给定的序列(字符串,字节,元组,列表或范围)或任何支持序列协议的对象。切片用于检索值的子集。基本切片技术是定义起点。
切片是一种从字符串和列表之类的数据类型中提取某些元素的方法。
语法:
slice[stop] slice[start:stop:step]
其他变化:
slice[start:stop] slice[start:] slice[:stop] slice[:] slice[start:stop:step]
Parameter(s):
start:对象切片开始的起始整数。
停止:整数,直到切片发生。切片在索引停止-1处停止。
step:整数值,该值确定要切片的每个索引之间的增量。
注意:如果传递单个参数,则start和step为None。
示例
-bash-4.2$ python3 Python 3.6.8 (default, Apr 25 2019, 21:02:35) [GCC 4.8.5 20150623 (Red Hat 4.8.5-36)] on linux Type "help", "copyright", "credits" or "license" for more information. >>> list = [1,2,3,4,5,6] >>> print(list[3:5]) [4, 5] # 这里从索引3到5的元素被提取并添加到列表中 >>> print(list[2:5:2]) [3, 5] # 这里从索引2到5的元素以2的步长被提取(每个第二个值) >>> print(list[1:]) [2, 3, 4, 5, 6] # 提取到最后一个索引 >>> print(list[:3]) [1, 2, 3] # 从初始(0th)索引中提取 >>>
以相反的顺序打印列表的值
使用负步长值,我们可以以相反的顺序打印列表中的项目。
示例
Python 3.6.8 (default, Apr 25 2019, 21:02:35) [GCC 4.8.5 20150623 (Red Hat 4.8.5-36)] on linux Type "help", "copyright", "credits" or "license" for more information. >>> list = [1,2,3,4,5,6] >>> print(list[-1:1:-1]) [6, 5, 4, 3] >>> print(list[::-1]) [6, 5, 4, 3, 2, 1] # 列表中所有元素的顺序颠倒 >>>
切片字符串值
切片也可以应用于字符串变量。考虑以下示例,
示例1:反转字符串
Python 3.6.8 (default, Apr 25 2019, 21:02:35) [GCC 4.8.5 20150623 (Red Hat 4.8.5-36)] on linux Type "help", "copyright", "credits" or "license" for more information. >>> test_str = "http://www.nhooo.com" >>> print(test_str[::-1]) moc.plehedulcni.www//:ptth >>>
示例2:获取顶级域
Python 3.6.8 (default, Apr 25 2019, 21:02:35) [GCC 4.8.5 20150623 (Red Hat 4.8.5-36)] on linux Type "help", "copyright", "credits" or "license" for more information. >>> test_str = "http://www.nhooo.com" >>> print(test_str[-4:]) .com >>>
示例3:使用协议打印URL
Python 3.6.8 (default, Apr 25 2019, 21:02:35) [GCC 4.8.5 20150623 (Red Hat 4.8.5-36)] on linux Type "help", "copyright", "credits" or "license" for more information. >>> test_str = "http://www.nhooo.com" >>> print(test_str[7:]) www.nhooo.com
示例4:打印不带协议或顶级域的URL
Python 3.6.8 (default, Apr 25 2019, 21:02:35) [GCC 4.8.5 20150623 (Red Hat 4.8.5-36)] on linux Type "help", "copyright", "credits" or "license" for more information. >>> test_str = "http://www.nhooo.com" >>> print(test_str[7:-4]) www.nhooo >>>