How do I get a substring of a string in Python?

前端 未结 13 1906
我寻月下人不归
我寻月下人不归 2020-11-22 00:32

Is there a way to substring a string in Python, to get a new string from the third character to the end of the string?

Maybe like myString[2:end]?

13条回答
  •  离开以前
    2020-11-22 01:20

    I would like to add two points to the discussion:

    1. You can use None instead on an empty space to specify "from the start" or "to the end":

      'abcde'[2:None] == 'abcde'[2:] == 'cde'
      

      This is particularly helpful in functions, where you can't provide an empty space as an argument:

      def substring(s, start, end):
          """Remove `start` characters from the beginning and `end` 
          characters from the end of string `s`.
      
          Examples
          --------
          >>> substring('abcde', 0, 3)
          'abc'
          >>> substring('abcde', 1, None)
          'bcde'
          """
          return s[start:end]
      
    2. Python has slice objects:

      idx = slice(2, None)
      'abcde'[idx] == 'abcde'[2:] == 'cde'
      

提交回复
热议问题