Didn"t forge
2009-03-19 17:29
采纳率: 25%
浏览 315

有没有办法在 Python 中子串一个字符串?

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

Maybe like myString[2:end]?

If leaving the second part means 'till the end', if you leave the first part, does it start from the start?

转载于:https://stackoverflow.com/questions/663171/is-there-a-way-to-substring-a-string-in-python

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

11条回答 默认 最新

  • larry*wei 2009-03-19 17:30
    已采纳
    >>> x = "Hello World!"
    >>> x[2:]
    'llo World!'
    >>> x[:2]
    'He'
    >>> x[:-2]
    'Hello Worl'
    >>> x[-2:]
    'd!'
    >>> x[2:-2]
    'llo Worl'
    

    Python calls this concept "slicing" and it works on more than just strings. Take a look here for a comprehensive introduction.

    点赞 评论
  • ?yb? 2009-03-19 17:31

    You've got it right there except for "end". It's called slice notation. Your example should read:

    new_sub_string = myString[2:]
    

    If you leave out the second parameter it is implicitly the end of the string.

    点赞 评论
  • 叼花硬汉 2009-03-19 18:02

    One example seems to be missing here: full (shallow) copy.

    >>> x = "Hello World!"
    >>> x
    'Hello World!'
    >>> x[:]
    'Hello World!'
    >>> x==x[:]
    True
    >>> 
    

    This is a common idiom for creating a copy of sequence types (not of interned strings). [:] Shallow copies a list, See python-list-slice-used-for-no-obvious-reason.

    点赞 评论
  • 七度&光 2012-03-02 05:19

    A common way to achieve this is by String slicing. MyString[a:b] gives you a substring from index a to (b - 1)

    点赞 评论
  • 北城已荒凉 2012-03-20 00:58

    Just for completeness as nobody else has mentioned it. The third parameter to an array slice is a step. So reversing a string is as simple as:

    some_string[::-1]
    

    Or selecting alternate characters would be:

    "H-e-l-l-o- -W-o-r-l-d"[::2] # outputs "Hello World"
    

    The ability to step forwards and backwards through the string maintains consistency with being able to array slice from the start or end.

    点赞 评论
  • 7*4 2012-08-04 11:43

    Substr() normally (i.e. PHP and Perl) works this way:

    s = Substr(s, beginning, LENGTH)
    

    So the parameters are beginning and LENGTH.

    But Python's behaviour is different; it expects beginning and one after END (!). This is difficult to spot by beginners. So the correct replacement for Substr(s, beginning, LENGTH) is

    s = s[ beginning : beginning + LENGTH]
    
    点赞 评论
  • MAO-EYE 2015-03-18 12:01

    Maybe I missed it, but I couldn't find a complete answer on this page to the original question(s) because variables are not further discussed here. So I had to go on searching.

    Since I'm not yet allowed to comment, let me add my conclusion here. I'm sure I was not the only one interested in it when accessing this page:

     >>>myString = 'Hello World'
     >>>end = 5
    
     >>>myString[2:end]
     'llo'
    

    If you leave the first part, you get

     >>>myString[:end]
     'Hello' 
    

    And if you left the : in the middle as well you got the simplest substring, which would be the 5th character (count starting with 0, so it's the blank in this case):

     >>>myString[end]
     ' '
    
    点赞 评论
  • 笑故挽风 2016-08-31 04:28

    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'
      
    点赞 评论
  • 妄徒之命 2016-08-31 04:50

    Using hardcoded indexes itself can be a mess.

    In order to avoid that, Python offers a built-in object slice().

    string = "my company has 1000$ on profit, but I lost 500$ gambling."
    

    If we want to know how many money I got left.

    Normal solution:

    final = int(string[15:19]) - int(string[43:46])
    print(final)
    >>>500
    

    Using slices:

    EARNINGS = slice(15, 19)
    LOSSES = slice(43, 46)
    final = int(string[EARNINGS]) - int(string[LOSSES])
    print(final)
    >>>500
    

    Using slice you gain readability.

    点赞 评论
  • 狐狸.fox 2017-06-23 21:53

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

    Maybe like myString[2:end]?

    Yes, this actually works if you assign, or bind, the name,end, to constant singleton, None:

    >>> end = None
    >>> myString = '1234567890'
    >>> myString[2:end]
    '34567890'
    

    Slice notation has 3 important arguments:

    • start
    • stop
    • step

    Their defaults when not given are None - but we can pass them explicitly:

    >>> stop = step = None
    >>> start = 2
    >>> myString[start:stop:step]
    '34567890'
    

    If leaving the second part means 'till the end', if you leave the first part, does it start from the start?

    Yes, for example:

    >>> start = None
    >>> stop = 2
    >>> myString[start:stop:step]
    '12'
    

    Note that we include start in the slice, but we only go up to, and not including, stop.

    When step is None, by default the slice uses 1 for the step. If you step with a negative integer, Python is smart enough to go from the end to the beginning.

    >>> myString[::-1]
    '0987654321'
    

    I explain slice notation in great detail in my answer to Explain slice notation Question.

    点赞 评论
  • 游.程 2018-10-17 12:32

    That's pretty simple:

    s = 'Hello, World!'
    print(s[:]) # prints "Hello, World!"
    print(s[:5]) # prints Hello
    print(s[5:]) # prints , World!
    print(s[3:7]) # prints "lo, "
    
    点赞 评论

相关推荐 更多相似问题