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

前端 未结 13 2138
我寻月下人不归
我寻月下人不归 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:04

    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.

提交回复
热议问题