python字符串切片笔记

字符串切片,即对字符串按照索引进行截取操作,获取想要的子串,分正向截取和逆向截取。
结合下面字符串索引示意图理解字符串正向索引和逆向索引:
字符串索引示意图
利用索引进行切片操作时,可包含三个参数:
str[start_index:end_index:step]

  1. start_index:起始位置,空时默认为0
  2. end_index:终止位置,空时默认为字符串/列表长度
  3. step:步长,空时默认为1,不能为0

来2个示例:

>>> s='I like python. I am learning python!'
# 正向输出
>>> s[::]
'I like python. I am learning python!'
# 逆向输出
>>> s[::-1]
'!nohtyp gninrael ma I .nohtyp ekil I'

start_index、end_index为0时:

  • 当 step>0,start_index 的空值下标为 0,end_index 的空值下标为 length,step 的方向是左到右;
  • 当 step<0,start_index 的空值下标为 length,end_index 的空值下标为 0,此时反向为右到左了!

也就是说 start_index、 end_index 空值代表的头和尾,是随着 step 的正负而改变的。
来一波示例供理解:

>>> s='I like python. I am learning python!'
>>> len(s)
36
# 正向输出:s[::],s[:36:]结果相同 
>>> s[:36:]
'I like python. I am learning python!'
# 逆向输出:s[::-1],s[-1::-1],s[-1:-37:-1],s[36::-1]结果相同
>>> s[::-1]
'!nohtyp gninrael ma I .nohtyp ekil I'
>>> s[-1::-1]
'!nohtyp gninrael ma I .nohtyp ekil I'
>>> s[-1:-37:-1]
'!nohtyp gninrael ma I .nohtyp ekil I'
>>> s[36::-1]
'!nohtyp gninrael ma I .nohtyp ekil I'
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值