Python string slice indices - slice to end of stri

2020-02-20 07:50发布

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.

word = "Help"
word[1:-1] # But I want to grab up to end of string!
word[1:len(word)] # Works but is there anything better?

标签: python string
7条回答
The star\"
2楼-- · 2020-02-20 08:01

Or even:

>>> word = "Help"
>>> word[-3:]
'elp'
查看更多
小情绪 Triste *
3楼-- · 2020-02-20 08:04

Are you looking for this?

>>> word = "Help"
>>> word[1:]
'elp'
查看更多
家丑人穷心不美
4楼-- · 2020-02-20 08:06

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'
查看更多
神经病院院长
5楼-- · 2020-02-20 08:13

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.

查看更多
Explosion°爆炸
6楼-- · 2020-02-20 08:14

Yes, of course, you should:

word[1:]
查看更多
聊天终结者
7楼-- · 2020-02-20 08:16

You can instead try using:

word[1:]
查看更多
登录 后发表回答