本站改版新增arduino频道
对字符串切片及翻转
给定一个字符串,从头部或尾部截取指定数量的字符串,然后将其翻转拼接。 实例 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
利用索引进行切片操作时,可包含三个参数:
如对列表来说即:list[start_index: stop_index: step]。
起始位置 : start_index (空时默认为 0)。
终点位置: stop_index (空时默认为列表长度) 需要注意起点与终点索引的位置关系。
步长: step (空时默认为 1,不能为 0)。
例如用于整个字符翻转:
def rotate(input):
print("字符翻转前: " + input)
input = input[:: -1]
print("字符翻转后: " + input)
if __name__ == "__main__":
input = 'Runoob'
rotate(input)
输出结果:
字符翻转前: Runoob
字符翻转后: boonuR
start_index、 stop_index 为 0 时:
当 step>0,start_index 的空值下标为 0,stop_index 的空值下标为 length,step 的方向是左到右;
当 step<0,start_index 的空值下标为 length,stop_index 的空值下标为 0,此时反向为右到左了!
也就是说 start_index、 stop_index 空值代表的头和尾,是随着 step 的正负而改变的。
s="hyl ekil ylemertxe ma i"
y=s[:2:-1]
print(y)
>>>i am extremely like
Copyright © 2014 ESP56.com All Rights Reserved
晋ICP备14006235号-22 晋公网安备14108102001165号
执行时间: 0.0096149444580078 seconds