zoukankan      html  css  js  c++  java
  • 基本的字符串之切片

    Python提供了5个字符串的基本操作符

    切片操作(slice)可以从一个字符串中获取子字符串(字符串的一部分)。我们使用一对方括号、起始偏移量start、终止偏移量end 以及可选的步长step 来定义一个分片。

    即[start:end:step]

    • 实行左闭右开原则
    • [:] 提取从开头(默认位置0)到结尾(默认位置-1)的整个字符串
    • [start:] 从start 提取到结尾
    • [:end] 从开头提取到end - 1
    • [start:end] 从start 提取到end - 1
    • [start:end:step] 从start 提取到end - 1,每step 个字符提取一个
    • 左侧第一个字符的位置/偏移量为0,右侧最后一个字符的位置/偏移量为-1

    例如:

    s="hello"
    t="world"
    s+=t
    print(s)
    print(s[-1])
    print(s[2:8])
    print(s[::3])
    print(s[-2::-1])

    分析:s[-1]表示s字符串逆序遍历的第一位字符即d。

       s[2:8]表示s字符串顺序从第2位字符遍历到第七位,因为实行左闭右开原则,即llowor。

       s[::3]表示s字符串顺序从头到尾每隔3个字符遍历,即hlod

       s[-2::-1]表示s字符串从倒数第二个字符逆序遍历,即lrowolleh

    运行结果:

  • 相关阅读:
    锋利的BFC
    inline和inline-block的间隙问题
    margin和padding的四种写法
    js中Math.round、parseInt、Math.floor和Math.ceil小数取整小结
    使用vscode自动编译less
    redux获取store中的数据
    react显示隐藏动画
    react使用路由
    react中使用fetchjsonp获取数据
    vue兼容到ie9
  • 原文地址:https://www.cnblogs.com/DrcProgrammingCool/p/11559640.html
Copyright © 2011-2022 走看看