Python string slice indices - slice to end of string

后端 未结 7 1745
粉色の甜心
粉色の甜心 2020-12-28 15:39

With string indices, is there a way to slice to end of string without using len()? Negative indices start from the end, but [-1] omits the final character.

w         


        
相关标签:
7条回答
  • 2020-12-28 16:08
    word="Help" 
    word[:]
    

    'Help'

    I hope this helps you

    0 讨论(0)
  • 2020-12-28 16:17

    Or even:

    >>> word = "Help"
    >>> word[-3:]
    'elp'
    
    0 讨论(0)
  • 2020-12-28 16:21

    You could always just do it like this if you want to only omit the first character of your string:

    word[1:]
    

    Here you are specifying that you want the characters from index 1, which is the second character of your string, till the last index at the end. This means you only slice the character at the first index of the string, in this case 'H'. Printing this would result in: 'elp'

    Not sure if that's what you were after though.

    0 讨论(0)
  • 2020-12-28 16:26

    You can instead try using:

    word[1:]
    
    0 讨论(0)
  • 2020-12-28 16:26

    I found myself needing to specify the end index as an input variable in a function. In that case, you can make end=None. For example:

    def slice(val,start=1,stop=None)
        return val[start:stop]
    
    word = "Help"
    slice(word)  # output: 'elp'
    
    0 讨论(0)
  • 2020-12-28 16:32

    Yes, of course, you should:

    word[1:]
    
    0 讨论(0)
提交回复
热议问题