• Python String Slicing


    Strings and Character Data in Python

    String Slicing

    Python also allows a form of indexing syntax that extracts substrings from a string, known as string slicing. If s is a string, an expression of the form s[m:n] returns the portion of s starting with position m, and up to but not including position n:

    s = 'foobar'
    s[2:5]
    #'oba'

    Remember: String indices are zero-based. The first character in a string has index 0. This applies to both standard indexing and slicing.

    Again, the second index specifies the first character that is not included in the result—the character 'r' (s[5]) in the example above. That may seem slightly unintuitive, but it produces this result which makes sense: the expression s[m:n] will return a substring that is n - m characters in length, in this case, 5 - 2 = 3.

    If you omit the first index, the slice starts at the beginning of the string. Thus, s[:m] and s[0:m] are equivalent:

    Similarly, if you omit the second index as in s[n:], the slice extends from the first index through the end of the string. This is a nice, concise alternative to the more cumbersome s[n:len(s)]:

    For any string s and any integer n (0 ≤ n ≤ len(s)), s[:n] + s[n:] will be equal to s:

    If the first index in a slice is greater than or equal to the second index, Python returns an empty string. This is yet another obfuscated way to generate an empty string, in case you were looking for one:

  • 相关阅读:
    移动端调试Vconsole
    Vue-返回顶部
    Vue-封装loading
    Vue-水印封装
    Vue-封装scroll触底
    微信小程序-图片上传
    前端面试题(2)
    前端常见面试题
    服务端渲染(SSR)和客户端(CSR)渲染的区别
    什么是模块化?模块化开发的好处
  • 原文地址:https://www.cnblogs.com/chucklu/p/16882828.html
Copyright © 2020-2023  润新知