Python string slice indices - slice to end of string

后端 未结 7 1861
粉色の甜心
粉色の甜心 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: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'
    

提交回复
热议问题